导入依赖
<!–spring boot 2.0以后默认使用lettuce–>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!–lettuce 依赖commons-pool–>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
application.yml中配置参数
spring:
redis:
cluster:
nodes:
- 192.168.1.7:6379
- 192.168.1.7:6379
# Redis默认情况下有16个分片,配置具体使用的分片,默认为0
database: 0
lettuce:
pool:
# 连接池最大连接数 默认8 ,负数表示没有限制
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认-1
max-wait: -1
# 连接池中的最大空闲连接 默认8
max-idle: 8
# 连接池中的最小空闲连接 默认0
min-idle: 0
Lettuce 配置类
@Configuration
public class LettuceConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String,Object> template = new RedisTemplate <>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
模拟service
@Service
@Slf4j
public class UserServiceImpl implements UserService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public String getString(String key) {
if(redisTemplate.hasKey(key)){
log.info(“redis中查找的信息”);
return (String) redisTemplate.opsForValue().get(key);
}else {
String val =”RedisTemplate”;
log.info(“mysql中查找的信息”);
redisTemplate.opsForValue().set(key,val);
log.info(“mysql中查询的信息存入Redis中”);
return val;
}
}
}
测试
@SpringBootTest
class SpringLettuceApplicationTests {
@Autowired
private UserService userService;
@Test
void contextLoads() {
String aaaa = userService.getString(“aaaa”);
System.out.println(aaaa);
}
}
成功连接数据库
2020-07-13 19:02:24.708 INFO 10772 — [ main] c.e.s.service.UserServiceImpl : redis中查找的信息
RedisTemplate
2020-07-13 19:02:24.746 INFO 10772 — [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService ‘applicationTaskExecutor’
————————————————
版权声明:本文为CSDN博主「l1306395862」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/l1306395862/article/details/107322150/