zoukankan      html  css  js  c++  java
  • 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);

    需要这么来存取。自行体会吧
    待补充。。。

  • 相关阅读:
    读写分离,就该这么改进
    使用HttpHandler来监控HTML页面请求
    半DDD架构 1
    WebForm开发中的路由功能
    如何让代码可测试化(C#)
    ParamQuery(jQuery Grid Plugin PQGrid, jQuery插件)
    通用Login功能自动化测试
    Top 10 Security Issue Solution
    KO学习重点
    OWASP Top 10 – 2013, 最新十大安全隐患(ASP.NET解决方法)
  • 原文地址:https://www.cnblogs.com/justtodo/p/12994933.html
Copyright © 2011-2022 走看看