应用场景
存放Token、存放用户信息或字典等需要频繁访问数据库获取但不希望频繁访问增加数据库压力且变化不频繁的数据。
集成步骤
1. 新建 Maven 项目并引入 redis 依赖【部分框架有可能已经集成,会导致依赖文件有差异】
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置 application.yml文件
#数据源配置
spring:
redis:
##redis 单机环境配置
# Redis服务器地址
host: 127.0.0.1
# Redis服务器连接端口
port: 6379
password:
# Redis数据库索引(默认为0)
database: 0
ssl: false
datasource:
url: jdbc:mysql://*.***.**.**:3516/smart_order?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
username: root
password: ******
3. 编写缓存服务和Controller
spring-boot 自动配置了 RedisConnectionFactory, StringRedisTemplate 和 RedisTemplate Bean。
默认,连接的 redis 服务端为 localhost:6379
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
import org.springframework.beans.factory.annotation.Autowired;
import