zoukankan      html  css  js  c++  java
  • 如何高雅的使用redis去获取一个值

    //场景,给定一个订单号来从缓存中查询一个订单信息;

     步骤: 1从redis中直接获取,有数据就返回

              2.如果redis中没有值,就查数据库

              3.数据库查到的数据不为空,就刷到redis中

             4.返回查到的数据

      一般的代码写法:

     public ShopOrderMast get(String orderId){
           // 1从redis中直接获取,有数据就返回
            String orderStr = redisUtil.string_get(orderId);
            if(StringUtils.isNotBlank(orderStr)){
                return JSON.parseObject(orderStr,ShopOrderMast.class);
            }
            // 2.如果redis中没有值,就查数据库
             ShopOrderMast orderMast = shopOrderMastMapper.selectOrderByCodOrderId(orderId);
    
            // 3.数据库查到的数据不为空,就刷到redis中
            if(null!=orderMast){
                redisUtil.string_set(orderId,JSON.toJSONString(orderMast),1000);
            }
           // 4.返回查到的数据
            return orderMast;
        }

    //优雅的做法
    public abstract class RedisCacheUtil {
    
        //从redis中获取
        public interface CacheFactory<K,V>{
    
            V get(K key);
        }
        //从数据库获取
        public interface RealObjectFactory<K,V>{
    
            V get(K key);
        }
        //刷到缓存
        public interface FlushCaheFactory<K,V>{
    
            void flush(K key,V v);
        }
        //获取缓存key的值
        public  static <K,V> V get(K key,CacheFactory<K,V> cacheFactory,RealObjectFactory<K,V> realFactory,FlushCaheFactory<K,V> flushCaheFactory){
            //先从缓存获取
            V v = cacheFactory.get(key);
            if(null!=v){
                return v;
            }
            //缓存不存在,就从数据库获取
            v = realFactory.get(key);
            if(null!=v){
                //重新刷到缓存
                flushCaheFactory.flush(key,v);
            }
            return v;
        }
    }

    //根据上面的工具类,改造获取订单的缓存方法,可以使用lambda表达式
     public ShopOrderMast getByRedis(String orderId){
          return RedisCacheUtil.get(orderId, key -> {
              String orderStr = redisUtil.string_get(orderId);
              if(StringUtils.isNotBlank(orderStr)){
                  return JSON.parseObject(orderStr,ShopOrderMast.class);
              }
              return null;
          }, key -> shopOrderMastMapper.selectOrderByCodOrderId(orderId),
                  (key, orderMast) -> redisUtil.string_set(orderId,JSON.toJSONString(orderMast),1000));}
    
    
    
     
    
    
    
     
  • 相关阅读:
    功能:Java注解的介绍和反射使用
    功能:@Vaild注解使用及扩展
    转载:微信小程序view布局
    功能:Java8新特性steam流
    功能:Linux运行jar包Shell脚本
    转载:Windows使用tail -f 监控文件
    转载:java.math.BigDecimal 比较大小
    问题:跨域及解决方案
    基于 @SelectProvider 注解实现无侵入的通用Dao
    SpringBoot中的异步操作与线程池
  • 原文地址:https://www.cnblogs.com/yangxiaohui227/p/11770459.html
Copyright © 2011-2022 走看看