Spring Boot + Redis
启动redis
docker run --name redisServer -P -d redis
redis自带客户端,启动客户端
docker run -it --link redisServer:db --entrypoint redis-cli redis -h db
也可以使用桌面工具Redis Desktop Manager测试
下载地址:https://redisdesktop.com/download
下载完后安装,打开程序
连接服务器
可以看到上面存进去的name
新建一个Spring Boot项目,pom.xml如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion> <groupId>org.mythsky</groupId>
<artifactId>spring-boot-redis-demo</artifactId>
<version>0.0.-SNAPSHOT</version>
<packaging>jar</packaging> <name>spring-boot-redis-demo</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.</version>
</dependency> <!--<dependency>-->
<!--<groupId>springboot.db</groupId>-->
<!--<artifactId>mysql</artifactId>-->
<!--<version>${project.version}</version>-->
<!--</dependency>-->
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
添加User
package org.mythsky.springbootredisdemo.domain; import java.io.Serializable;
import java.util.Date;
import java.util.List; public class User implements Serializable {
private Long id;
private String name;
private Date createDate;
private Department department;
private List<Role> roles; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Date getCreateDate() {
return createDate;
} public void setCreateDate(Date createDate) {
this.createDate = createDate;
} public Department getDepartment() {
return department;
} public void setDepartment(Department department) {
this.department = department;
} public List<Role> getRoles() {
return roles;
} public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
Department
package org.mythsky.springbootredisdemo.domain; import java.io.Serializable; public class Department implements Serializable {
private Long id;
private String name; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
Role
package org.mythsky.springbootredisdemo.domain; import java.io.Serializable; public class Role implements Serializable {
private Long id;
private String name; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
RedisConfig
package org.mythsky.springbootredisdemo.config; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; @Configuration
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory(){
JedisConnectionFactory redisConnectionFactory=new JedisConnectionFactory();
redisConnectionFactory.setHostName("192.168.31.146");
redisConnectionFactory.setPort();
redisConnectionFactory.setUsePool(true);
return redisConnectionFactory;
}
@Bean
public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory factory){
StringRedisTemplate template=new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper=new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
UserRedis
package org.mythsky.springbootredisdemo.service; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.mythsky.springbootredisdemo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils; import java.util.List;
import java.util.concurrent.TimeUnit; @Repository
public class UserRedis {
@Autowired
private RedisTemplate<String,String> redisTemplate; public void add(String key,Long time,User user){
Gson gson=new Gson();
redisTemplate.opsForValue().set(key,gson.toJson(user),time, TimeUnit.MINUTES);
} public void add(String key, Long time, List<User> users){
Gson gson=new Gson();
redisTemplate.opsForValue().set(key,gson.toJson(users),time, TimeUnit.MINUTES);
} public User get(String key){
Gson gson=new Gson();
User user=null;
String userJson=redisTemplate.opsForValue().get(key);
if(!StringUtils.isEmpty(userJson)){
user=gson.fromJson(userJson,User.class);
}
return user;
} public List<User> getList(String key){
Gson gson=new Gson();
List<User> users=null;
String listJson=redisTemplate.opsForValue().get(key);
if(!StringUtils.isEmpty(listJson)){
users=gson.fromJson(listJson,new TypeToken<List<User>>(){}.getType());
}
return users;
} public void delete(String key){
redisTemplate.opsForValue().getOperations().delete(key);
}
}
SpringBootRedisDemoApplicationTests
package org.mythsky.springbootredisdemo; import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mythsky.springbootredisdemo.config.RedisConfig;
import org.mythsky.springbootredisdemo.domain.Department;
import org.mythsky.springbootredisdemo.domain.Role;
import org.mythsky.springbootredisdemo.domain.User;
import org.mythsky.springbootredisdemo.service.UserRedis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList;
import java.util.Date;
import java.util.List; @RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRedisDemoApplicationTests { private static Logger logger= LoggerFactory.getLogger(SpringBootRedisDemoApplicationTests.class);
@Autowired
UserRedis userRedis;
@Before
public void setup(){
Department department=new Department();
department.setName("开发部"); Role role=new Role();
role.setName("admin"); User user=new User();
user.setName("user");
user.setCreateDate(new Date());
user.setDepartment(department); List<Role> roles=new ArrayList<Role>();
roles.add(role); user.setRoles(roles); userRedis.delete(this.getClass().getName()+":userByName:"+user.getName());
userRedis.add(this.getClass().getName()+":userByName:"+user.getName(),10l,user);
}
@Test
public void get() {
User user=userRedis.get(this.getClass().getName()+":userByName:user");
Assert.assertNotNull(user);
logger.info("======user====== name:{}, department:{}, role:{}",user.getName(),user.getDepartment(),user.getRoles().get().getName());
} }
运行,可以在测试窗口看到结果
此时再打开桌面客户端
连接redis集群
官方文档:
最主要的是设置RedisConnectionFactory
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
config
@Component
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class ClusterConfigurationProperties { /*
* spring.redis.cluster.nodes[0] = 127.0.0.1:7379
* spring.redis.cluster.nodes[1] = 127.0.0.1:7380
* ...
*/
List<String> nodes; /**
* Get initial collection of known cluster nodes in format {@code host:port}.
*
* @return
*/
public List<String> getNodes() {
return nodes;
} public void setNodes(List<String> nodes) {
this.nodes = nodes;
}
}
@Configuration
public class AppConfig { /**
* Type safe representation of application.properties
*/
@Autowired
ClusterConfigurationProperties clusterProperties;
@Value("${spring.redis.password}")
private String password; public @Bean
RedisConnectionFactory connectionFactory() {
RedisClusterConfiguration configuration=new RedisClusterConfiguration(clusterProperties.getNodes());
configuration.setPassword(RedisPassword.of(password));
return new JedisConnectionFactory(configuration);
}
}
配置文件
spring.redis.cluster.nodes=172.20.102.65:7001,172.20.102.65:7002,172.20.102.65:7003,172.20.102.66:7004,172.20.102.66:7005,172.20.102.66:7006
spring.redis.password=123456
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisDemoApplicationTests { @Test
public void contextLoads() {
String result= stringRedisTemplate.opsForValue().get("api:tmp:users:1375bf2a-8e03-4097-8e1f-803787b6fac2");
System.out.println(result);
}
@Test
public void test1(){
String result=redisTemplate.opsForValue().get("api:tmp:users:1375bf2a-8e03-4097-8e1f-803787b6fac2");
System.out.println(result);
}
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String,String> redisTemplate;
}
Spring Boot + Redis的更多相关文章
- spring boot redis缓存JedisPool使用
spring boot redis缓存JedisPool使用 添加依赖pom.xml中添加如下依赖 <!-- Spring Boot Redis --> <dependency> ...
- spring boot + redis 实现session共享
这次带来的是spring boot + redis 实现session共享的教程. 在spring boot的文档中,告诉我们添加@EnableRedisHttpSession来开启spring se ...
- Spring Boot 项目学习 (三) Spring Boot + Redis 搭建
0 引言 本文主要介绍 Spring Boot 中 Redis 的配置和基本使用. 1 配置 Redis 1. 修改pom.xml,添加Redis依赖 <!-- Spring Boot Redi ...
- Spring Boot Redis 集成配置(转)
Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...
- spring boot redis 缓存(cache)集成
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- spring boot redis分布式锁
随着现在分布式架构越来越盛行,在很多场景下需要使用到分布式锁.分布式锁的实现有很多种,比如基于数据库. zookeeper 等,本文主要介绍使用 Redis 做分布式锁的方式,并封装成spring b ...
- 从.Net到Java学习第四篇——spring boot+redis
从.Net到Java学习系列目录 “学习java已经十天,有时也怀念当初.net的经典,让这语言将你我相连,怀念你......”接上一篇,本篇使用到的框架redis.FastJSON. 环境准备 安装 ...
- Spring Boot Redis Cluster 实战干货
添加配置信息 spring.redis: database: 0 # Redis数据库索引(默认为0) #host: 192.168.1.8 #port: 6379 password: 123456 ...
- Spring boot redis自增编号控制 踩坑
近段期间,公司 接手一个订单号生成服务,规则的话已经由项目经理他们规定好了,主要是后面的四位数代表的关于当前订单号已经执行第几个了.而这里面有一个要求就是支持分布式.为了实现这个东西,刚开始我使用了r ...
随机推荐
- 学以致用十八-----shell脚本之基础概念及变量
1.脚本脚本,说了很多年的脚本,一直都没怎么弄明白为什么叫脚本,还仅仅是script翻译过来的?今天再查看翻译,查阅了资料,对脚本有了个新的认识. script也叫剧本,脚本---剧本,像剧本一样,让 ...
- python计算机硬件基础以及变量常量常量池,解释器编译器比较,python的两种运行方式
1.什么是编程语言 语言是一个事物与另外一个事物沟通的介质 编程语言是程序员与计算机沟通的介质 2.什么是编程 编程就是程序按照某种编程语言的语法规范将自己想要让计算机做的事情表达出来 表达的结果就是 ...
- Ng第六课:逻辑回归(Logistic Regression)
6.1 分类问题 6.2 假说表示 6.3 判定边界 6.4 代价函数 6.5 简化的成本函数和梯度下降 6.6 高级优化 6.7 多类分类:一个对所有 6.1 分类问题 在分类问题中 ...
- C++函数的传值调用&指针调用&引用调用
目录 传值调用 指针调用 引用调用 传值调用 该方法把参数的实际值复制给函数的形式参数.在这种情况下,修改函数内的形式参数对实际参数没有影响. #include<iostream> usi ...
- java实现在图片上编辑文本内容
package com.yin.text; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; impor ...
- set_time_limit
语法 : void set_time_limit (int seconds)说明 : 设定一个程式所允许执行的秒数,如果到达限制的时间,程式将会传回错误.它预设的限制时间是30秒,max_execut ...
- Windows 8.1 Update中的小改变
在Build 2014大会中,发布了Windows 8.1 Update的更新,并将于4月8日通过Windows Update进行推送.但是,在MSDN订阅下载中,带有该更新的镜像已经可以在4月3号放 ...
- logrotate 日志切割工具
相关原理参见:https://www.cnblogs.com/sailrancho/p/4784763.html 一.相关目录: 程序:/usr/sbin/logrotate配置:/etc/logro ...
- cxGrid动态设置单元格对齐方式
cxGrid动态设置单元格对齐方式 2013年10月08日 00:52:49 踏雪无痕 阅读数:2150更多 个人分类: cxGrid 判断: //uses cxTextEditcxGrid1DB ...
- PCA in MLLib
SVD分解: \(A=U\Sigma V^T\),变换:\(\hat{A}=A\cdot V=U\Sigma\) 分解时先计算\(A^TA=U\Sigma^2U^T\),再进行SVD分解 /** * ...