欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot配置Redis自定義過期時間操作

 更新時間:2021年07月28日 11:19:15   作者:悅瀾群書  
這篇文章主要介紹了SpringBoot配置Redis自定義過期時間操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

SpringBoot配置Redis自定義過期時間

Redis配置依賴

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-redis</artifactId>
        <version>1.4.4.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.8.1.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.9.0</version>
</dependency>

SpringBoot-Reids配置文件

package com.regs.tms.common.redis;
@Configuration
@EnableCaching// 啟用緩存,這個注解很重要
@ConfigurationProperties(prefix = "spring.redis")
@Data
public class RedisCacheConfig extends CachingConfigurerSupport {
	private String host;
	private Integer port;
	private Integer database;
	private String password;

	@Bean("redisTemplate")
	public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
	    StringRedisTemplate template = new StringRedisTemplate();
	    template.setConnectionFactory(factory);
	    //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值
	    Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
	    ObjectMapper mapper = new ObjectMapper();
	    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
	    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
	    serializer.setObjectMapper(mapper);
	    template.setValueSerializer(serializer);
	    template.setHashValueSerializer(serializer);
	    // 設置鍵(key)的序列化采用StringRedisSerializer。
	    template.setKeySerializer(new StringRedisSerializer());
	    template.setHashKeySerializer(new StringRedisSerializer());
	    //打開事務支持
	    template.setEnableTransactionSupport(true);
	    template.afterPropertiesSet();
	    return template;
	}

	@Bean
	public PlatformTransactionManager transactionManager(DataSource dataSource) throws SQLException {
	    //配置事務管理器
	    return new DataSourceTransactionManager(dataSource);
	}

	@Bean("stringRedisTemplate")
	public StringRedisTemplate stringRedisTemplate() {
	    Integer port = this.port == null ? 6379 : this.port;
	    JedisConnectionFactory jedis = new JedisConnectionFactory();
	    jedis.setHostName(host);
	    jedis.setPort(port);
	    if (StringUtils.isNotEmpty(password)) {
	        jedis.setPassword(password);
	    }
	    if (database != null) {
	        jedis.setDatabase(database);
	    } else {
	        jedis.setDatabase(0);
	    }
	    // 初始化連接pool
	    jedis.afterPropertiesSet();
	    // 獲取連接template
	    StringRedisTemplate temple = new StringRedisTemplate();
	    temple.setConnectionFactory(jedis);
	    return temple;
	}
}

自定義失效注解

package com.regs.tms.common.redis.annotation;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface CacheDuration {
    //Sets the expire time (in seconds).
    public long duration() default 60;
}

自定義失效配置

package com.regs.tms.common.redis.annotation;
 /**
 * ExpireCacheManager,繼承自RedisCacheManager,
 * 用于對@CacheExpire解析及有效期的設置
 */
public class RedisExpireCacheManager extends RedisCacheManager implements ApplicationContextAware, InitializingBean {
    private ApplicationContext applicationContext;

    public RedisExpireCacheManager(RedisTemplate redisTemplate) {
        super(redisTemplate);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() {
        parseCacheExpire(applicationContext);
    }

    private void parseCacheExpire(ApplicationContext applicationContext) {
        final Map<String, Long> cacheExpires = new HashMap<>(16);
        //掃描有注解
        String[] beanNames = applicationContext.getBeanNamesForAnnotation(Cacheable.class);
        for (String beanName : beanNames) {
            final Class clazz = applicationContext.getType(beanName);
            addCacheExpires(clazz, cacheExpires);
        }
        //設置有效期
        super.setExpires(cacheExpires);
    }

    private void addCacheExpires(final Class clazz, final Map<String, Long> cacheExpires) {
        ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                ReflectionUtils.makeAccessible(method);
                //根據(jù)CacheExpire注解獲取時間
                CacheExpire cacheExpire = findCacheExpire(clazz, method);
                if (cacheExpire != null) {
                    Cacheable cacheable = findAnnotation(method, Cacheable.class);
                    String[] cacheNames = isEmpty(cacheable.value()) ? new String[]{} : cacheable.value();
                    for (String cacheName : cacheNames) {
                        cacheExpires.put(cacheName, cacheExpire.expire());
                    }
                }
            }
        }, new ReflectionUtils.MethodFilter() {
            @Override
            public boolean matches(Method method) {
                return null != findAnnotation(method, Cacheable.class);
            }
        });
    }

    /**
     * CacheExpire標注的有效期,優(yōu)先使用方法上標注的有效期
     *
     * @param clazz
     * @param method
     * @return
     */
    private CacheExpire findCacheExpire(Class clazz, Method method) {
        CacheExpire methodCache = findAnnotation(method, CacheExpire.class);
        if (null != methodCache) {
            return methodCache;
        }
        CacheExpire classCache = findAnnotation(clazz, CacheExpire.class);
        if (null != classCache) {
            return classCache;
        }
        return null;
    }
}

spring boot 使用redis 超時時間重新設置

如果要計算每24小時的下單量,

通常的做法是,取出舊值,進行加一在設置回去,

但是這樣就出現(xiàn)了一個問題

第二次設置值的時候,把超時時間重新設置成個24小時

這樣無疑的記錄24小時的數(shù)量是不準確的

并且spring boot 中,默認使用了spring 來操作redis ,使存在每個redis中的值,都會加前面加入一些東西

1) "\xac\xed\x00\x05t\x00\x0bREDISUALIST"

我們在查找每個值的時候,并不知道在key前面需要加點什么.

所以我們必須要用keys 這個命令 ,來匹配 我們需要查找的key,來取第一個

然后我們用 ttl 命令 返回指定key的剩余時間 ,重新設置回去,而不是設置24小時,這樣就實現(xiàn)了24小時累加一次

在redisService 中,增加一個方法

/**
     * 獲取指定key的剩余超時時間,key最好是唯一的,有特點的,最好不要匹配出多個 例子 *111 取出 "\xac\xed\x00\x05t\x00\x0b111"
     * 返回剩余秒數(shù)
     * @param key
     * @return
     * create by jcd
     */
    public Long ttlByKey(@NotNull String key){
        Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys(key.getBytes());
        byte[] bytes = keys.stream().findFirst().get();
        Long ttl = redisTemplate.getConnectionFactory().getConnection().ttl(bytes);
        return ttl;
    }

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • java this super使用方法詳解

    java this super使用方法詳解

    Java中this、super關鍵字的用法簡單說明:super是Java語言的保留字,用來指向類的超類,本文將詳細介紹,需要的朋友可以參考下
    2012-12-12
  • 淺談java中的對象、類、與方法的重載

    淺談java中的對象、類、與方法的重載

    本文主要對java中的對象、類、與方法的重載進行簡要概述,具有一定的參考價值,需要的朋友一起來看下吧
    2016-12-12
  • 利用java實現(xiàn)二維碼和背景圖的合并

    利用java實現(xiàn)二維碼和背景圖的合并

    本文介紹如何使用java代碼將自動生成的二維碼放入背景模板中,對于java學習者或許有幫助,一起來看看。
    2016-07-07
  • Mybatis返回結果封裝map過程解析

    Mybatis返回結果封裝map過程解析

    這篇文章主要介紹了Mybatis返回結果封裝map過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-09-09
  • Java實現(xiàn)讀取和寫入properties文件

    Java實現(xiàn)讀取和寫入properties文件

    這篇文章主要介紹了Java實現(xiàn)讀取和寫入properties文件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • Java8深入學習系列(二)函數(shù)式編程

    Java8深入學習系列(二)函數(shù)式編程

    函數(shù)式編程,這個詞語由兩個名詞構成,函數(shù),編程。編程這個詞我就不用解釋了,大家都是做這個的。函數(shù),其實單獨抽離出來這個詞語,也并不陌生,那二者組合后的到底是什么呢,下面這篇文章主要給大家介紹了關于Java8函數(shù)式編程的相關資料,需要的朋友可以參考下。
    2017-08-08
  • SpringMVC中的ConversionServiceExposingInterceptor工具類解析

    SpringMVC中的ConversionServiceExposingInterceptor工具類解析

    這篇文章主要介紹了SpringMVC中的ConversionServiceExposingInterceptor工具類解析,ConversionServiceExposingInterceptor是Spring MVC的一個HandlerInterceptor,用于向請求添加一個屬性,需要的朋友可以參考下
    2023-12-12
  • java構造方法的互相調用方式

    java構造方法的互相調用方式

    這篇文章主要介紹了java構造方法的互相調用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • Java socket字節(jié)流傳輸示例解析

    Java socket字節(jié)流傳輸示例解析

    這篇文章主要為大家詳細介紹了Java socket字節(jié)流傳輸示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • java實現(xiàn)文件上傳、下載、圖片預覽

    java實現(xiàn)文件上傳、下載、圖片預覽

    這篇文章主要介紹了java實現(xiàn)文件上傳、下載、圖片預覽,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-01-01

最新評論