Spring Bootはredisを統合し、redisServiceを実現し、データキャッシュ時間を動的に設定する


1.maven依存のインポート


     org.springframework.boot
     spring-boot-starter-redis

2、springbootのredis環境アプリケーションを配置する.ymlファイル
spring:
  redis:
    host: 106.14.72.179
    password: redispassword
    port: 6379
    pool:
      max-idle: 100
      min-idle: 1
      max-active: 1000
      max-wait: -1

3、構成クラスの作成、redis関連の設定
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    /**
     *   key   
     * @return
     */
    @Bean
    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
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        return rcm;
    }

    /**
     * RedisTemplate  
     */
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        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);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

4、RedisServiceインタフェースの作成
/**
 * @author [email protected]
 * @date 2018/7/17 15:59
 */
public interface RedisService {
    public boolean set(final String key , Object value);

    /**
     *           
     * @param key
     * @param value
     * @param expireTime
     * @return
     */
    public boolean set(final String key , Object value , Long expireTime);

    /**
     *        value
     * @param keys
     */
    public void remove(final String... keys);

    /**
     *     key
     * @param pattern
     */
    public void removePattern(final String pattern);
    /**
     *      value
     * @param key
     */
    public void remove(final String key);
    /**
     *            value
     * @param key
     * @return
     */
    public boolean exists(final String key);
    /**
     *     
     * @param key
     * @return
     */
    public Object get(final String key);
    /**
     *      
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value);

    /**
     *       
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey);

    /**
     *     
     * @param k
     * @param v
     */
    public void lPush(String k,Object v);
    /**
     *     
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List lRange(String k, long l, long l1);

    /**
     *     
     * @param key
     * @param value
     */
    public void add(String key,Object value);

    /**
     *     
     * @param key
     * @return
     */
    public Set setMembers(String key);
    /**
     *       
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key,Object value,double scoure);

    /**
     *       
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set rangeByScore(String key,double scoure,double scoure1);
}

5、RedisServiceインタフェース実装クラスRedisServiceImplを作成し、関連インタフェースを実現する
/**
 * Redis service  
 * @author [email protected]
 * @date 2018/7/17 15:59
 */
@Service
public class RedisServiceImpl implements RedisService {
    public final static Logger logger = LoggerFactory.getLogger(RedisServiceImpl.class);

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     *     
     * @param key
     * @param value
     * @return Boolean
     */
    public boolean set(final String key , Object value){
        boolean result = false;
        try {
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key , value);
            result = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     *           
     * @param key
     * @param value
     * @param expireTime
     * @return
     */
    public boolean set(final String key , Object value , Long expireTime){
        boolean result = false;
        try {
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key , value);
            redisTemplate.expire(key , expireTime , TimeUnit.MILLISECONDS);
            result = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     *        value
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     *     key
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }
    /**
     *      value
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }
    /**
     *            value
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    /**
     *     
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
    /**
     *      
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value){
        HashOperations hash = redisTemplate.opsForHash();
        hash.put(key,hashKey,value);
    }

    /**
     *       
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey){
        HashOperations  hash = redisTemplate.opsForHash();
        return hash.get(key,hashKey);
    }

    /**
     *     
     * @param k
     * @param v
     */
    public void lPush(String k,Object v){
        ListOperations list = redisTemplate.opsForList();
        list.rightPush(k,v);
    }

    /**
     *     
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List lRange(String k, long l, long l1){
        ListOperations list = redisTemplate.opsForList();
        return list.range(k,l,l1);
    }

    /**
     *     
     * @param key
     * @param value
     */
    public void add(String key,Object value){
        SetOperations set = redisTemplate.opsForSet();
        set.add(key,value);
    }

    /**
     *     
     * @param key
     * @return
     */
    public Set setMembers(String key){
        SetOperations set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     *       
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key,Object value,double scoure){
        ZSetOperations zset = redisTemplate.opsForZSet();
        zset.add(key,value,scoure);
    }

    /**
     *       
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set rangeByScore(String key,double scoure,double scoure1){
        ZSetOperations zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }
}

6、RedisServiceを呼び出してビジネスロジックを実現する.
/**
 * @author [email protected]
 * @date 2018/7/17 15:05
 */
@Controller
@RequestMapping("api/hello")
public class HelloWordController {

    @Autowired
    private RedisService redisService;

    @RequestMapping("index")
    @ResponseBody
    public String get(){

        //   
        redisService.set("my_weixin_gzh" , "     :    (javamanual)");
        //   key,         ,     
        redisService.set("my_weixin_gzh" , "     :    (javamanual)" , 10000);
        return "     :    (javamanual)";
    }
}