Spring Boot專案開發(八)——使用redis快取
阿新 • • 發佈:2020-12-08
一、新增redis相關依賴
<!--新增redis相關依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
二、配置redis連線資訊
#配置redis連線資訊
spring.redis.host=192.168.211.128
spring.redis.port=6379
spring.redis.password=
三、編寫redis配置檔案
package com.learn.mall.config; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory;import java.time.Duration; @Configuration @EnableCaching public class CachingConfig { @Bean public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory){ RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory); RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); //設定快取過期時間,此處為30秒 cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(30)); RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter,cacheConfiguration); return redisCacheManager; } }
四、開啟快取
在專案啟動類中新增@EnableCaching註解,開啟快取
package com.learn.mall; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @MapperScan(basePackages = "com.learn.mall.model.dao") @EnableSwagger2 @EnableCaching public class MallApplication { public static void main(String[] args) { SpringApplication.run(MallApplication.class, args); } }
五、使用快取
新增@Cacheable註解,使用快取;value為快取的key。注意:實體類需要實現Serializable介面
@Override @Cacheable(value = "listForCustom") public List<CategoryVO> listForCustom(){ List<CategoryVO> categoryVOList = new ArrayList<>(); recursivelyFindCategories(categoryVOList,0); return categoryVOList; }
六、檢視redis快取資訊