📕 SpringBoot集成Redis Cluster 集群
我打算创建一个专栏,主要用于结合八股文和各种场景题来进行代码实践,包括但不限制于集成各种中间件去实现对应的场景和工具封装,该文章为SpringBoot专栏的一个系列,希望大家观看以后帮我多多点赞评论。
大家的点赞和关注是我创作的动力,实属不易,谢谢大家~
📕 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.11.1</version>
</dependency>
📕 application.properties增加redis cluster配置信息
# redis cluster
spring.redis.cluster.nodes=192.168.150.15:7001,192.168.150.17:7002,192.168.150.19:7003,192.168.150.15:8001,192.168.150.17:8002,192.168.150.19:8003
spring.redis.cluster.max-redirects=5
spring.redis.password=root@1234
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.enabled=true
📕 Redis 序列化
package com.yjren.yjrenweb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
//设置key序列化方式String
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置value的序列化方式json,使用GenericJackson2JsonRedisSerializer替换默认的序列化
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
// 实现分片集群读写分离
@Bean
public LettuceClientConfigurationBuilderCustomizer lettuceConnectionFactory() {
return clientConfigurationBuilder -> clientConfigurationBuilder.readFrom(ReadFrom.REPLICA_PREFERRED);
}
}
📕 测试Redis存储
@SpringBootTest
public class TestApplication {
@Resource
private UserMapper userMapper;
@Resource
private RedisTemplate<String,Object> redisTemplate;
@Test
public void redisTest(){
List<User> userList = userMapper.getAllUser();
redisTemplate.opsForValue().set("yjren", JSON.toJSONString(userList));
redisTemplate.expire("yjren",30, TimeUnit.SECONDS);
}
}