java_redis快速使用

新建一个枚举用来管理redis的过期时间

package com.shareworx.apm.datacenter.redisCache;

import java.util.concurrent.TimeUnit;

/**
 * redis缓存时间控制枚举
 */


public enum CacheKeyPrefix {

    TestRedis("test_redis", "测试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;
    }

}

注入服务

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> 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 result = cacheTest.opsForValue().get(cacheKey);
        for (String s : result) {
            System.out.println(s);
            str = str + " " + s;
        }
        return str;
    }
}

但是因为序列化方式是jdk的,所以用Redisdeskmanager等软件连接,看到的是乱码,故而要进行序列化后操作

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 {

    /**
     * 注意设置过期时间
     */
//    @Bean
//    public CacheManager cacheManager(RedisTemplate redisTemplate) {
//        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
//        Map expires = new HashMap<>();
//        expires.put("access_token_cache", 1800L);//过期时间秒为单位,默认为30分钟
//        expires.put("nonce_cache", 600L);//默认为10分钟
//        expires.put("allotting_autocancel", 300L);//默认五分钟
//        cacheManager.setExpires(expires);
//        return cacheManager;
//    }
    @Bean(name = "apmRedisTemplate")
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
//        StringRedisTemplate template = new StringRedisTemplate(factory);
////        template.setConnectionFactory(factory);
//        //key序列化
//        RedisSerializer redisSerializer = new StringRedisSerializer();

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

        return template;
    }

}
 

                            
                        
                    
                    
                    

你可能感兴趣的:(java_redis快速使用)