1、引入依赖
<!-- 引入 spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
2、编写application.yml配置文件
spring:
application:
name: spring-boot-redis-demo #应用名
redis:
#url: "redis://user:password@example.com:6379" # 此配置可覆盖 host,post,password 配置
database: 0 # redis 数据库下标(操作的是0号数据库(默认),一共有16个数据库)
host: {主机地址} # redis 数据库主机地址
port: 6379 # redis 数据库端口
password: {密码} # redis 数据库密码(没有密码可不配置)
timeout: 6000 # 获取连接超时时间
ssl: false # 是否开启 SSL 支持
lettuce: # lettuce 是基于 Netty 实现的 redis 客户端,spring boot 默认使用此客户端
pool:
max-active: 8 # 规定时间内连接池能够分配的连接的最大数量
max-idle: 8 # 连接池中允许空闲连接的最大数量
min-idle: 0 # 连接池中允许空闲连接的最小数量
max-wait: -1ms #连接分配最大等待时间,负数表示一直等待分配连接
#time-between-eviction-runs: # 回收空闲连接线程执行时间间隔
#cluster: # redis cluster配置。
# max-redirects: 100 # 跨集群执行命令时要遵循的最大重定向数。
# nodes: # Redis集群服务列表(可配置多个)
# - "host:port"
#sentinel: # redis 哨兵配置
# master: # redis 服务器名字
# password: # redis 哨兵密码
# nodes: # redis 哨兵各节点(可配置多个)
3、编写controller类
spring-boot 自动配置了 RedisConnectionFactory, StringRedisTemplate 和 RedisTemplate Bean。
这里建议把RedisTemplate对象换成StringRedisTemplate对象,这样就不需要配置类,并且可以和客户端同步。
CacheService 接口:
/**
* 缓存服务
* @param <K> 缓存的 key
* @param <V> 缓存的内容
*/
public interface CacheService<K,V> {
Boolean cache(K key, V value);
Boolean remove(K key);
V get(K key);
}
RedisCacheService类:
/**
* 基于 Redis 实现的的缓存服务
*/
@Service("redisCacheService")
public class RedisCacheService implements CacheService<String, Object>{
// spring-boot 自动配置了 RedisConnectionFactory, StringRedisTemplate 和 RedisTemplate Bean。
@Autowired
private RedisConnectionFactory connectionFactory;
@Autowired
private StringRedisTemplate template;
@Autowired
@Qualifier("redisTemplate")
private RedisTemplate redisTemplate;
@Override
public Boolean cache(String key, Object value) {
template.opsForValue().set(key,String.valueOf(value));
return Boolean.TRUE;
}
@Override
public Boolean remove(String key) {
return template.delete(key);
}
@Override
public Object get(String key) {
return template.opsForValue().get(key);
}
}
CacheController类:
/**
* CacheController 用于提供 接口进行缓存操作
*/
@RestController
@RequestMapping("/cache")
public class CacheController {
@Autowired
@Qualifier("redisCacheService")
private CacheService cacheService;
/**
* 缓存
* @param key
* @param value
* @return
*/
@GetMapping("/save")
public Boolean cache(@RequestParam("key") String key, @RequestParam("value")String value){
return cacheService.cache(key,value);
}
/**
* 查询
* @param key 缓存key
* @return
*/
@GetMapping("/get")
public Object get(@RequestParam("key") String key){
return cacheService.get(key);
}
/**
* 删除缓存
* @param key 缓存key
* @return
*/
@GetMapping("/remove")
public Boolean remove(@RequestParam("key") String key){
return cacheService.remove(key);
}
}