一。安装
- 下载Redis,下载地址:https://github.com/MicrosoftArchive/redis/releases
- zip包解压后,在当前地址栏输入cmd后,执行redis的启动命令:redis-server.exe redis.windows.conf
- 客户端连接,D: oolsRedis-x64-3.2.100>redis-cli.exe -h 127.0.0.1 -p 6379
二。redis缓存使用
1.1 配置application.yml
spirng:
redis:
database: 1
host: 127.0.0.1
port: 6379
password:
1.2 增加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
springboot自动提供了StringRedisTemplate和RedisTemplate
1.5 启动类打开缓存开关EnableCaching
@SpringBootApplication @MapperScan("com.yjm.sell.dao") @EnableCaching public class SellApplication {
1.6 使用@Cacheable, @CachePut, @Cacheable
@Cacheable(cacheNames = "product", key = "#productId", condition = "#productId.length()>5") public ProductInfoDO selectById(String productId) {
redis中可以是cacheNames :key, 缓存没有时会进入方法并将值放入缓存,下次缓存有就直接从缓存取
condition表示条件满足才使用缓存
@CacheEvict(cacheNames = "product", key="123") public int insertSelective(ProductInfoDO record) { // TODO Auto-generated method stub return productInfoDOMapper.insertSelective(record); }
@CacheEvict:执行完会将缓存中的这个删除
@CachePut:每次进入都会将返回值放入缓存