redis使用時需要注意的問題


redis在現在的項目中經常出現,但是伴隨着一波又一波的新人進入這個行業,一些問題被一次又一次的暴露。

說明在使用一個東西之前,充分了解到會帶來什么影響,是十分重要的。

眾所周知,redis是一個內存數據庫,相較於磁盤數據庫,其讀取速度之快,讓宅男們自慚形穢。

redis的應用場景,主要就是為了減輕對后端服務的壓力,最終提高一定的性能。但若使用不當,出現問題時,即使拍斷大腿,不照樣造成一定的后果了嗎。

剛好最近在使用redis,就簡單聊聊:

大家都知道redis支持多種數據結構的存儲,但是只了解這些是不夠的。

場景一:我需要存一個數組對象的結構進redis,直接set是不行的,我使用的是spring-data-redis這個依賴,

 在RedisTemplate類的源碼里,有這樣一段描述:

Note that while the template is generified, it is up to the serializers/deserializers to properly convert the given
Objects to and from binary data.
大意是:當需要自定義Redis對象時:需要指定序列化和反序列化的類型。上代碼:
@Configuration
public class RedisConfig{
    @Bean
    public RedisTemplate<String,ResultList> redisTemplateList(RedisConnectionFactory factory){
        RedisTemplate<String,ResultList>template=new RedisTemplate<>();
        //關聯
        template.setConnectionFactory(factory);
        //設置key的序列化器
        template.setKeySerializer(new StringRedisSerializer());
        //設置value的序列化器
        template.setValueSerializer(new Jackson2JsonRedisSerializer<>(ResultList.class));
        return template;
    }
}

public class ResultList implements Serializable {

private List<Result> resultList;
private String id;
  //構造就省略了,貼這個代碼是體現,redis里面set的值是自定義的結構。方便業務中用,其中Result是一個實體對象
}
 
上偽代碼,看如何使用:
ResultList zx  = new ResultList();
Sring cacheKey = "keyId";//根據業務場景自定義的唯一key
if (this.redisTemplateList.opsForList().range(cacheKey, 0, -1).size() == 0) {   /**業務查詢代碼*/ zx = new ResultList(***); this.redisTemplateList.opsForList().rightPush(cacheKey, zx); log.info("當前查詢不走緩存,結果存入緩存,key:" + cacheKey); /** 動態維護 redis 超時時間*/ this.redisTemplateList.expire(cacheKey, 30L, TimeUnit.MINUTES); } else {   log.info("當前查詢結果在緩存中存在,key:" + cacheKey); zx = redisTemplateList.opsForList().range(cacheKey, 0, -1).get(0);   }
這就完成了一個自定義的類型在redis中的存儲,方便取用。如果你也想自定義一個結構,就把上面代碼里的RedisTemplate中,設置value的序列化器自行更改即可。
還要注意一個點,如果存的是對象結構
this.redisTemplate.opsForValue().get(key)
this.redisTemplate.opsForValue().set(key,value);

需要這么來存取。自行體會吧
待補充。。。


免責聲明!

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



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