Springboot2.x使用redis作為緩存
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號”
優(yōu)質(zhì)文章,第一時間送達(dá)
? 作者?|??瘋子110
來源 |? urlify.cn/6zMVfi
66套java從入門到精通實(shí)戰(zhàn)課程分享?
一、Springboot2.x關(guān)于配置redis作為緩存。
基本配置如下:
(1)在application.properties文件中
spring.redis.database=2 //第幾個數(shù)據(jù)庫,由于redis中數(shù)據(jù)庫不止一個
spring.redis.host=localhost // 也可指定為127.0.0.1
spring.redis.port=6379 // 默認(rèn)端口
spring.redis.password= // 默認(rèn)為空
#?springboot2.x以上如此配置,由于2.x的客戶端是lettuce
#?單位要帶上
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-wait=10000ms
spring.redis.lettuce.shutdown-timeout=100ms
#?springboot1.x如此配置,由于1.x的客戶端是jedis
#spring.redis.jedis.pool.max-active=8
#spring.redis.jedis.pool.min-idle=0
#spring.redis.jedis.pool.max-idle=8
#spring.redis.jedis.pool.max-wait=-1
#spring.redis.timeout=500(2)在pom.xml中
????????<dependency>
????????????<groupId>org.apache.commonsgroupId>
????????????<artifactId>commons-pool2artifactId>
????????????<version>2.4.2version>
????????dependency>
????????<dependency>
????????????<groupId>org.springframework.bootgroupId>
????????????<artifactId>spring-boot-starter-data-redisartifactId>
????????dependency>
????????<dependency>
????????????<groupId>org.springframework.bootgroupId>
????????????<artifactId>spring-boot-starter-cacheartifactId>
????????dependency>(3)自定義緩存管理器RedisCacheConfig
package?com.xf.spring_test.config;
import?org.slf4j.Logger;
import?org.slf4j.LoggerFactory;
import?org.springframework.cache.annotation.CachingConfigurerSupport;
import?org.springframework.cache.annotation.EnableCaching;
import?org.springframework.cache.interceptor.KeyGenerator;
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.connection.RedisConnectionFactory;
import?org.springframework.data.redis.serializer.*;
import?java.time.Duration;
@Configuration
@EnableCaching
public?class?RedisCacheConfig?extends?CachingConfigurerSupport?{
????private?static?final?Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class);
????// 自定義key生成器
????@Bean
????public?KeyGenerator keyGenerator(){
????????return?(o, method, params) ->{
????????????StringBuilder sb = new?StringBuilder();
????????????sb.append(o.getClass().getName()); // 類目
????????????sb.append(method.getName()); // 方法名
????????????for(Object param: params){
????????????????sb.append(param.toString()); // 參數(shù)名
????????????}
????????????return?sb.toString();
????????};
????}
????// 配置緩存管理器
????@Bean
????public?RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory)?{
????????RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
????????????????.entryTtl(Duration.ofSeconds(60)) // 60s緩存失效
????????????????// 設(shè)置key的序列化方式
????????????????.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
????????????????// 設(shè)置value的序列化方式
????????????????.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
????????????????// 不緩存null值
????????????????.disableCachingNullValues();
????????RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
????????????????.cacheDefaults(config)
????????????????.transactionAware()
????????????????.build();
????????logger.info("自定義RedisCacheManager加載完成");
????????return?redisCacheManager;
????}
??/* @Bean
????public RedisTemplate
????// key鍵序列化方式
????private?RedisSerializer keySerializer()? {
????????return?new?StringRedisSerializer();
????}
????// value值序列化方式
????private?GenericJackson2JsonRedisSerializer valueSerializer(){
????????return?new?GenericJackson2JsonRedisSerializer();
????}
}(4)在service的實(shí)現(xiàn)類中加入需要的注解,即可實(shí)現(xiàn)緩存數(shù)據(jù)
package?com.xf.spring_test.service.impl;
import?com.xf.spring_test.dao.PersonDao;
import?com.xf.spring_test.domain.Person;
import?com.xf.spring_test.service.UserService;
import?org.springframework.cache.annotation.CacheEvict;
import?org.springframework.cache.annotation.CachePut;
import?org.springframework.cache.annotation.Cacheable;
import?org.springframework.stereotype.Service;
import?java.util.List;
@Service
public?class?UserServiceImpl?implements?UserService?{
????PersonDao personDao;
????public?UserServiceImpl(PersonDao personDao)?{
????????this.personDao = personDao;
????}
????@Override
????@Cacheable(cacheNames = "user")
????public?Person getUserById(Integer id)?{
????????return?personDao.getUserById(id);
????}
????@Override
????@Cacheable(cacheNames = "users")
????public?List getAllUser()? {
????????return?personDao.getAllUser();
????}
????@Override
????@CachePut(cacheNames = "updateUser", condition = "#person!=null", unless = "#result>0")
????public?Integer editUser(Person person)?{
????????return?personDao.editUser(person);
????}
????@Override
????@CacheEvict(cacheNames = "delUser", allEntries = true, beforeInvocation = true,
????condition = "#userId>0")
????public?Integer delUser(Integer userId)?{
????????return?personDao.delUser(userId);
????}
}?二、注意事項(xiàng)
(1)要緩存的JAVA對象必須實(shí)現(xiàn)Serailizable接口
(2)必須要配置RedisCacheManager?來管理緩存


??? ?
感謝點(diǎn)贊支持下哈?
評論
圖片
表情
