spring-boot-starter-data-redis
- https://blog.csdn.net/yeyinglingfeng/article/details/87790700?spm=1005.2026.3001.5635&utm_medium=distribute.pc_relevant_ask_down.none-task-blog-2defaultOPENSEARCHdefault-10.pc_feed_download_top3ask&depth_1-utm_source=distribute.pc_relevant_ask_down.none-task-blog-2defaultOPENSEARCHdefault-10.pc_feed_download_top3ask
依赖 lettuce
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
配置
spring:
redis:
host: localhost
port: 6379
password:
lettuce:
pool:## 默认配置
max-active: 8
max-idle: 8
min_idle: 0
max-wait: -1ms
cluster:
nodes:
- 127.0.0.1:6379
- 127.0.0.1:6380
序列化
- key序列化 : StringRedisSerializer
- 值序列换: JdkSerializationRedisSerializer(默认),Jackson2JsonRedisSerializer(推荐)
@Bean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// Jackson2JsonRedisSerializer<Object> jackson = new Jackson2JsonRedisSerializer<>(Object.class);
GenericJackson2JsonRedisSerializer jackson = new GenericJackson2JsonRedisSerializer();
template.setKeySerializer(RedisSerializer.string());
template.setKeySerializer(RedisSerializer.string());
template.setValueSerializer(jackson);
template.setHashValueSerializer(jackson);
return template;
}
- JdkSerializationRedisSerializer 默认,需要对象实现Serializable接口
- Jackson2JsonRedisSerializer 和 GenericJackson2JsonRedisSerializer
- Jackson2JsonRedisSerializer json序列化。反序列化泛型、数组的数据时为hashmap,因此反序列会报错
- GenericJackson2JsonRedisSerializer 类json序列化,会存储每个value的数据类型
- 后者内存消耗大,效率低
- 发布订阅
- 使用场景:全局缓存(一般redis)和局部缓存(一般为本地jvm内存)的数据同步
- 命令行: PUBLISH runoobChat "Redis PUBLISH test
- 命令行: SUBSCRIBE runoobChat
// 发布数据
redisTemplate.convertAndSend(channel, value);
/**
消费订阅数据
*/
@Bean
public RedisMessageListenerContainer messageListenerContainer(RedisConnectionFactory redisConnectionFactory, RedisRouteDefinitionListenerHander handler) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
// 可以修改成 patternTopic, 看一看 MessageListener 中监听的数据 msg.getBody是发布的数据
// msg.getTopic
container.addMessageListener(
(msg, pattern) -> handler.handle(msg, new String(pattern, StandardCharsets.UTF_8)),
new PatternTopic(Constants.REDIS_TOPIC_GATEWAY_PATTERN));
return container;
}
- 分布式锁
- 命令
SET resource-name anystring NX EX max-lock-time
是一种在 Redis 中实现锁的简单方法。 - http://doc.redisfans.com/string/set.html
- ValueOperations.setIfAbsent(key, val, time, unit)
- 自增
- ValueOperations.increment()
- 消息队列(生产者和消费者模式)
- list map set string
- http://doc.redisfans.com/string
- 集群部署
- spring-redis