SpringBoot整合Redis
Redis简介
REmote DIctionary Server(Redis) 是一个由 Salvatore Sanfilippo 写的 key-value 存储系统,是跨平台的非关系型数据库。Redis 是一个开源的使用 ANSI C 语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式、可选持久性的键值对(Key-Value)存储数据库,并提供多种语言的 API。Redis 通常被称为数据结构服务器,因为值(value)可以是字符串(String)、哈希(Hash)、列表(list)、集合(sets)和有序集合(sorted sets)等类型。
导入依赖
<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>
配置yml
spring:
redis:
database: 0 #Redis数据库索引(默认为0)
host: 127.0.0.1 #Redis服务器地址
port: 6379 #Redis服务器连接端口
lettuce:
pool:
max-active: 8 #连接池最大连接数(使用负值表示没有限制)
max-wait: 10000ms #最大阻塞等待时间(负数表示没有限制)
max-idle: 50 #连接池中的最大空闲连接
min-idle: 5 #连接池中的最小空闲连接
编写自己的redisTemplate
@Configuration
@EnableCaching
public class RedisConfig {
/**
* 编写自己的redisTemplate
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(final RedisConnectionFactory redisConnectionFactory) {
final RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
//对Key和Value进行序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
//对HashMap进行序列化
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
//设置连接工厂
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
添加与使用
将数据添加到redis中(在service层)
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public String getContentByType(final String type) {
final String contentByType = this.systemConfigMapper.getContentByType(type);
this.redisTemplate.opsForValue().set("system" + type, contentByType);
return contentByType;
}
取出使用(在controller层),通过key取出,判断是否为空,不为空则直接返回,相反则须在数据库中查询返回
@ApiOperation("查找配置信息")
@GetMapping("/seekContent/{type}")
public String getContentByType(@PathVariable("type") final String type) {
log.info("进入了查找配置信息接口");
final Object o = this.redisTemplate.opsForValue().get("system" + type);
if (o != null) {
return JSON.toJSONString(o);
}
return JSON.toJSONString(this.systemConfigService.getContentByType(type));
}
欢迎大家加入qq交流群:251413523,一起学习一起秃头。