springboot redisTemplate 外部反序列化


import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 外部反序列化
 *
 */
@Component
public class RedisTools<T> {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 存儲
     *
     * @param key
     * @param instance 類對象
     * @param timeOut 超時時間 單位/小時
     */
    public void set(String key, T instance, int timeOut){
        String value = JSON.toJSONString(instance);
        redisTemplate.opsForValue().set(key, value, timeOut, TimeUnit.HOURS);
    }

    /**
     * 獲取
     *
     * @param key
     * @param clazz
     */
    public T get(String key, Class<T> clazz){
        String value = redisTemplate.boundValueOps(key).get();
        if(value == null) return null;
        return JSON.parseObject(value, clazz);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM