java_redis快速使用

新建一個(gè)枚舉用來(lái)管理redis的過(guò)期時(shí)間

package com.shareworx.apm.datacenter.redisCache;

import java.util.concurrent.TimeUnit;

/**
 * redis緩存時(shí)間控制枚舉
 */


public enum CacheKeyPrefix {

    TestRedis("test_redis", "測(cè)試redis使用", TimeUnit.SECONDS.toSeconds(10))
    ;

    private CacheKeyPrefix(String key, String desc) {
        this.key = key;
        this.desc = desc;
    }

    private CacheKeyPrefix(String value, String desc, long timeout) {
        this.key = value;
        this.desc = desc;
        this.timeout = timeout;
    }

    private String key;
    private String desc;
    private long timeout;


    public String getKey() {
        return key;
    }

    public String getDesc() {
        return desc;
    }

    public long getTimeout() {
        return timeout;
    }

}

注入服務(wù)

package com.shareworx.apm.datacenter.redisCache;

import org.assertj.core.util.Lists;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "/redis")
public class RedisCacheAction {

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, List<String>> cacheTest;


    @GetMapping(value = "/test1/{cacheKey}")
    public String test1(@PathVariable String cacheKey) {
        cacheTest.opsForValue().set(cacheKey, Lists.newArrayList("111223", "中文中文"), CacheKeyPrefix.TestRedis.getTimeout(), TimeUnit.SECONDS);
        return "緩存成功,key:" + cacheKey;
    }

    @GetMapping(value = "/test2/{cacheKey}")
    public String test2(@PathVariable String cacheKey) {
        String str = "";
        if (!cacheTest.hasKey(cacheKey)) {
            str = "null";
            return str;
        }
        List<String> result = cacheTest.opsForValue().get(cacheKey);
        for (String s : result) {
            System.out.println(s);
            str = str + " " + s;
        }
        return str;
    }
}

但是因?yàn)樾蛄谢绞绞莏dk的,所以用Redisdeskmanager等軟件連接,看到的是亂碼,故而要進(jìn)行序列化后操作

package com.shareworx.apm.datacenter.redisCache;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

/**
 * Redis緩存配置類
 *
 */
@Configuration
@EnableCaching
public class RedisConfigurer extends CachingConfigurerSupport {

    /**
     * 注意設(shè)置過(guò)期時(shí)間
     */
//    @Bean
//    public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
//        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
//        Map<String, Long> expires = new HashMap<>();
//        expires.put("access_token_cache", 1800L);//過(guò)期時(shí)間秒為單位,默認(rèn)為30分鐘
//        expires.put("nonce_cache", 600L);//默認(rèn)為10分鐘
//        expires.put("allotting_autocancel", 300L);//默認(rèn)五分鐘
//        cacheManager.setExpires(expires);
//        return cacheManager;
//    }
    @Bean(name = "apmRedisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
//        StringRedisTemplate template = new StringRedisTemplate(factory);
////        template.setConnectionFactory(factory);
//        //key序列化
//        RedisSerializer<String> redisSerializer = new StringRedisSerializer();

        //value序列化,value hashmap序列化
        Jackson2JsonRedisSerializer<Object> 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);
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 五種數(shù)據(jù)結(jié)構(gòu)簡(jiǎn)介 Redis是使用C編寫的,內(nèi)部實(shí)現(xiàn)了一個(gè)struct結(jié)構(gòu)體redisObject對(duì)象,通過(guò)結(jié)構(gòu)體...
    彥幀閱讀 7,167評(píng)論 0 14
  • 1.1 資料 ,最好的入門小冊(cè)子,可以先于一切文檔之前看,免費(fèi)。 作者Antirez的博客,Antirez維護(hù)的R...
    JefferyLcm閱讀 17,320評(píng)論 1 51
  • 包含的重點(diǎn)內(nèi)容:JAVA基礎(chǔ)JVM 知識(shí)開源框架知識(shí)操作系統(tǒng)多線程TCP 與 HTTP架構(gòu)設(shè)計(jì)與分布式算法數(shù)據(jù)庫(kù)知...
    消失er閱讀 4,554評(píng)論 1 10
  • 1.Redis使用 Redis基礎(chǔ)教程 Redis簡(jiǎn)介: Redis是一個(gè)由ANSI C語(yǔ)言編寫,性能優(yōu)秀、支持網(wǎng)...
    抄無(wú)止境閱讀 1,384評(píng)論 0 3
  • NOSQL類型簡(jiǎn)介鍵值對(duì):會(huì)使用到一個(gè)哈希表,表中有一個(gè)特定的鍵和一個(gè)指針指向特定的數(shù)據(jù),如redis,volde...
    MicoCube閱讀 4,160評(píng)論 2 27

友情鏈接更多精彩內(nèi)容