一、引入pom
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
二、配置YML文件(二选一)
1.sentinel模式
server: port: 80 spring: redis: sentinel: nodes: 192.168.0.106:26379,192.168.0.106:26380,192.168.0.106:26381 //哨兵的ip和端口 master: mymaster //这个就是哨兵配置文件中 sentinel monitor mymaster 192.168.0.103 6379 2 配置的mymaster
2.Cluster模式
server:
port: 80
spring:
redis:
cluster:
nodes: 192.168.0.106:7000,192.168.0.106:7001,192.168.0.106:7002,192.168.0.106:7003,192.168.0.106:7004,192.168.0.106:7005
三、配置RedisTemplate模版
个人认为
setKeySerializer
setValueSerializer
不设置也可以,不过在使用的时候,需要自行将keyvalue 转换为json字符串后存入
@Configuration public class RedisConf { @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { Jackson2JsonRedisSerializer serializer=new Jackson2JsonRedisSerializer(Object.class); RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); template.setKeySerializer(serializer); //设置key序列化 template.setValueSerializer(serializer);//设置value序列化
return template; } }
四、测试(简单的model就省略了)
@RestController public class RedisTestController { @Autowired RedisTemplate redisTemplate; @GetMapping("set") public void set(){ redisTemplate.opsForValue().set("key1","123"); User u=new User(); u.setId(1); u.setName("name姓名"); redisTemplate.opsForValue().set("user",u); } @GetMapping("get") public Map get(){ Map map=new HashMap(); map.put("v1",redisTemplate.opsForValue().get("key1")); map.put("v2",redisTemplate.opsForValue().get("user")); return map; } }