spirngboot2.3.0 +Cache + Redis 实现注解缓存

8 篇文章 0 订阅
4 篇文章 1 订阅

1. 在pom.xml中 引入redis依赖

 <!-- 缓存依赖 -->
 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
  </dependency>
<!-- redis -->  
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
  </dependency>
    <!--spring2.0集成redis所需common-pool2-->
  <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
      <version>2.8.0</version>
  </dependency>
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

2. yml 配置

server:
  port: 16379


spring:
  
  cache:
    type: redis
    redis:
      cache-null-values: true # 表示是否缓存空值,一般情况下是允许的.如果设置false即不允许缓存空值,这样会导致很多请求数据库没有的数据时,不会缓存到redis导致每次都会请求到数据库。这种情况即:缓存穿透。
      time-to-live: 30m # 缓存超时时间ms
#      use-key-prefix: true #启用前缀
#      key-prefix: key #前缀
  redis:
    ##########redis 单例 ###########
    host: 127.0.0.1
    port: 6379
    ##########redis 单例 ###########
    timeout: 60s # 数据库连接超时时间,springboot2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
    database: 0
    ##########redis 集群###########
#    cluster:
#      nodes: 192.168.3.157:7000,192.168.3.158:7000,192.168.3.159:7000,192.168.3.157:7001,192.168.3.158:7001,192.168.3.159:7001
    ##########redis 集群###########
    lettuce:  # 连接池配置,springboot2.0中直接使用jedis或者lettuce配置连接池
      pool:
        max-active: -1 # 最大活跃连接数,负数为不限制
        max-idle: 500 # 最大空闲连接数
        min-idle: 50 # 等待可用连接的最大时间,负数为不限制
        max-wait: -1s # 等待可用连接的最大时间,负数为不限制


logging:
  pattern:
    level: info
#    dateformat: yyy-MM-dd HH:mm:ss

3. java启动类 须使用@EnableCaching才可启用 注解缓存

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@EnableCaching
@SpringBootApplication
public class OpenReidsApplication {

    public static void main(String[] args) {
        SpringApplication.run(OpenReidsApplication.class, args);
    }

}

4. 自定义缓存管理器RedisCacheConfig


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
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.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;
import java.time.Duration;

@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {



    @Bean(name = "redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringSerializer);
        template.setValueSerializer(stringSerializer);
        template.setHashKeySerializer(stringSerializer);
        template.setHashValueSerializer(stringSerializer);
        template.setConnectionFactory(factory);
        return template;
    }

    @Bean
    /**  自定义key生成器 */
    public KeyGenerator KeyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    @Bean
    /**  redis-cache configuration */
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 配置序列化(解决乱码的问题)
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                // 30分钟 缓存过期时间
                .entryTtl(Duration.ofMillis(30))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

5. 使用缓存 测试

@RestController
@CacheConfig(cacheNames = "test")
public  class RedisTestCtl {

    @RequestMapping(value = "/list")
    @Cacheable(key = "#p0" )
    public String list(int id,String name) {
        return "list-"+name;
    }
    @RequestMapping(value = "/add")
    @CachePut(key = "#id")
    public String add(int id,String name) {
        return "add-"+ name;
    }

    @RequestMapping(value = "/edit")
    @CachePut( key = "#id")
    public String edit(int id,String name) {
        return "edit-"+ name;
    }

    @RequestMapping(value = "/del")
    @CacheEvict(key = "#id")
    public String del(String id) {
        return "del-"+id;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值