zoukankan      html  css  js  c++  java
  • spring集成Redis注解缓存

    作为苦逼的程序猿,有时候我们需要给自己减压,对于数据库查询或者调用第三方查询 一些不经常变动的信息,但是这些查询又是很频繁,这时候我们可能会用到缓存。spring+Redis给我们提供了一个很简单的注解缓存。接下来让我们看看多门的简单

    直接上干货:

    Redis配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:redis="http://www.springframework.org/schema/redis"
           xmlns:cache="http://www.springframework.org/schema/cache"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
            http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
            http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis-1.0.xsd"
           >
    
    
        <cache:annotation-driven/>
    
        <bean id="redisConnectionFactory"
              class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
            <property name="hostName" value="${redis.hostName}"/>
            <property name="port" value="${redis.port}"/>
            <property name="password" value="${redis.password}"/>
            <property name="database" value="${redis.database}"/>
            <property name="poolConfig">
                <bean class="redis.clients.jedis.JedisPoolConfig">
                    <property name="maxTotal" value="${redis.pool.maxTotal}"/>
                    <property name="maxIdle" value="${redis.pool.maxIdle}"/>
                    <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}"/>
                    <property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"/>
                    <property name="minEvictableIdleTimeMillis" value="${redis.pool.minEvictableIdleTimeMillis}"/>
                    <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
                </bean>
            </property>
        </bean>
    
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory" ref="redisConnectionFactory"/>
            <property name="keySerializer">
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
            </property>
            <property name="valueSerializer">
                <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
            </property>
            <property name="hashKeySerializer">
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
            </property>
            <property name="hashValueSerializer">
                <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
            </property>
        </bean>
    
    
    </beans>

    Java配置代码

    1、前缀配置(此项可以更好的从可视化Redis工具如:rdm中查看缓存信息)

    public class MyRedisPrefix implements RedisCachePrefix {
        private final RedisSerializer serializer;
        private final String delimiter;
    
        public MyRedisPrefix() {
            this(":");
        }
    
        public MyRedisPrefix(String delimiter) {
            this.serializer = new StringRedisSerializer();
            this.delimiter = delimiter;
        }
    
        @Override
        public byte[] prefix(String cacheName) {
            return this.serializer.serialize(this.delimiter != null ? this.delimiter.concat(":").concat(cacheName).concat(":") : cacheName.concat(":"));
        }
    
    
    }

    2、缓存key值及其时间配置

    @Configuration
    public class RedisCacheConfig {
    
        private static long ONE_DAY = 60L * 60L * 24L;
    
        private static final String projectName = "test";
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Bean
        public CacheManager cacheManager() {
            RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    
            Map<String, Long> expires = new HashMap<>();
    
            expires.put("cache_something", ONE_DAY);
    
            // 设置超时
            cacheManager.setExpires(expires);
    
            // 没有设置的缓存默认过期时间
            cacheManager.setDefaultExpiration(60);
            cacheManager.setCachePrefix(new RedisPrefix(projectName));
            cacheManager.setUsePrefix(true);
    
            return cacheManager;
        }
    }

    3、缓存服务类

    @Service
    public class CacheService {
    
        @Cacheable(value = "cache_something", key = "'something'", unless = "#result == null")
        public String getCacheSomething() {
            String something = getSomething();
            return something;
        }
    
        private String getSomething() {
            String something = "this is something " + DateUtils.formatTime(new Date());
            System.out.println("【测试缓存】未进入缓存,实时查询结果:{}" + something);
            return something;
        }
      @CacheEvict(value = "voucherstype", key = "'list'", allEntries = true)
      public String deleteCacheSomething(String something) {
      System.out.println("【测试缓存】删除缓存:{}" + something);
      return "delete something ";
      }
    }

    4、调用缓存服务

    public class TestCache extends SpringBaseHttpTest {
    
        @Autowired
        private CacheService cacheService;
    
    
        @org.junit.Test
        public void testcache() throws Exception {
            cacheService.getCacheSomething();
         //
    cacheService.deleteCacheSomething();
    } } 

     5、核心的三个注解:

      @Cachable 根据方法的请求参数对其结果进行缓存

        参数说明:

        Key:缓存的 Key,可以为空,如果指定要按照 SPEL 表达式编写,如果不指定,则按照方法的所有参数进行组合。

        Value:缓存的名称,根据 RedisCacheConfig 中的配置做一些统一配置。

        Condition:缓存的条件,可以为空,使用 SPEL 编写,返回 true 或者 false,只有为 true 才进行缓存。

      @CachePut 根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用,再将结果放入缓存。

        参数说明:跟@Cachable相同

      @CacheEvict 根据条件对缓存进行清空

        参数说明:

        Key:同@Cachable。

        Value:同@Cachable。

        Condition:同@Cachable。

        allEntries:是否清空所有缓存内容,默认为 false,如果指定为 true,则方法调用后将立即清空所有缓存。

        beforeInvocation:是否在方法执行前就清空,默认为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存。默认情况下,如果方法执行抛出异常,则不会清空缓存

      

  • 相关阅读:
    【九】纯配置版本的微服务
    Eclipse 项目导航字体设置 左侧树字体
    【八】Spring Cloud Config
    Lua Table 操作
    根据角度和距离生成游戏物体(以圆心向圆圈线上生成物体)
    Unity UI和引用的管理中心
    利用三角函数实现按钮上下漂浮
    DoTween学习笔记(二) UGUI结合使用(实现一些简单效果)
    DoTween学习笔记(一)
    人物角色群体攻击判定四(三角区域判断)
  • 原文地址:https://www.cnblogs.com/xingtangxiaoga/p/11686355.html
Copyright © 2011-2022 走看看