首页 > 数据库 >redis缓存key工具类

redis缓存key工具类

时间:2023-05-17 11:00:31浏览次数:40  
标签:缓存 return String cache redis private key public store

package store.b2c.c.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 门店商品信息
 */

@Component
public class StoreProductCacheKeyService {
    private static String ALL_STORE_PRODUCT_LIST = "store_prd_%s"; //门店所有商品列表cache key
    private static String STORE_GROUP_IDS = "store_group_ids_%s"; //门店组列表cache key
    private static String STORE_PRODUCT_SALE_DATE = "store_prd_sale_date_%s"; //门店的销量和时间 cache KEY
    private static String STORE_PRODUCT_PRICE = "store_prd_price_%s"; //查询商品实时价格 cache KEY  %s是商品skuid
    /**
     * 门店所有商品列表缓存时间
     */
    @Value("${store.product.cache.baseExpire:180}")
    private int baseExpire;//过期 秒
    /**
     * 门店组时间
     */
    @Value("${store.product.cache.storeGroupIdsExpire:600}")
    private int storeGroupIdsExpire;//秒
    /**
     * 销量和上架时间
     */
    @Value("${store.product.cache.storeProductSaleAndDateExpire:3600}")
    private int storeProductSaleAndDateExpire;//秒


    /**
     * 商品实时价格缓存时间
     */
    @Value("${store.product.cache.storeProductPriceExpire:300}")
    private int storeProductPriceExpire;//秒

    /**
     * 随机缓存 时间
     */
    @Value("${store.product.cache.randomExpire:60}")
    public int randomExpire;//随机过期 秒


    @Value("${store.product.cache.open:true}")
    private Boolean open;//是否打开缓存  true打开  false关闭

    private Random random = new Random();

    public Boolean getOpen() {
        return open;
    }

    /**
     * 获取门店所有商品列表key
     *
     * @param storeId
     * @return
     */
    public static String getAllStoreProductList(Long storeId) {
        return String.format(ALL_STORE_PRODUCT_LIST, storeId);
    }


    /**
     * 获取门店组缓存key
     *
     * @param storeId
     * @return
     */
    public static String getStoreGroupIds(Long storeId) {
        return String.format(STORE_GROUP_IDS, storeId);
    }

    /**
     * 销量和上架时间
     *
     * @param storeId
     * @return
     */
    public static String getStoreProductSaleDate(Long storeId) {
        return String.format(STORE_PRODUCT_SALE_DATE, storeId);
    }

    /**
     * 商品实时价格缓存
     *
     * @param skuId
     * @return
     */
    public static String getStoreProductPrice(Long skuId) {
        return String.format(STORE_PRODUCT_PRICE, skuId);
    }

    /**
     * 获取所有门店商品 缓存时间 s
     *
     * @return
     */
    public int getAllExpire() {
        return baseExpire + random.nextInt(randomExpire);
    }

    public int getStoreGroupIdsExpire() {
        return storeGroupIdsExpire + random.nextInt(randomExpire);
    }

    public int getStoreProductSaleAndDateExpire() {
        return storeProductSaleAndDateExpire + random.nextInt(randomExpire);
    }

    public int getStoreProductPriceExpire() {
        return storeProductPriceExpire + random.nextInt(randomExpire);
    }

}

使用缓存

 private void saveQuerySkuPriceCache(Map<Long, PriceDto> priceDtoMap) {
        if (!storeProductCacheKeyService.getOpen()) {
            return;
        }
        for (Map.Entry<Long, PriceDto> priceDtoEntry : priceDtoMap.entrySet()) {
            redisUtils.setStrEx(StoreProductCacheKeyService.getStoreProductPrice(priceDtoEntry.getKey()), JsonUtils.toJson(priceDtoEntry.getValue()), storeProductCacheKeyService.getStoreProductPriceExpire());
        }
    }

    private List<Long> getNeedQuerySkuIdList(List<Long> skuIdList, Map<Long, PriceDto> priceDtoMap) {
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(skuIdList) || MapUtils.isEmpty(priceDtoMap)) {
            return skuIdList;
        }
        return skuIdList.stream()
                .filter(skuId -> priceDtoMap.get(skuId) == null)
                .collect(Collectors.toList());
    }

    private Map<Long, PriceDto> querySkuPriceFromCache(List<Long> skuIds) {

        Map<Long, PriceDto> cacheProductDetailDtoMap = new HashMap<>(10);//保存查询缓存数据中的商品数据
        if (!storeProductCacheKeyService.getOpen()) {
            return cacheProductDetailDtoMap;
        }
        List<String> redisCacheKeyList = buildAllRedisCacheKey(skuIds);
        List<String> cacheValueList = redisUtils.mGetStr(redisCacheKeyList);
        if (log.isDebugEnabled()) {
            log.debug("querySkuPriceFromCache={}", JsonUtils.toJson(cacheValueList));
        }
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(cacheValueList)) {
            for (String cacheValue : cacheValueList) {
                PriceDto priceDto = JsonUtils.fromJson(cacheValue, PriceDto.class);
                if (priceDto != null) {
                    cacheProductDetailDtoMap.put(priceDto.getSkuId(), priceDto);
                }
            }
        }
        return cacheProductDetailDtoMap;
    }

    private List<String> buildAllRedisCacheKey(List<Long> skuIdList) {
        List<String> redisCacheKeyList = new ArrayList<>();//批量查询的所有商品key
        for (Long skuid : skuIdList) {
            redisCacheKeyList.add(StoreProductCacheKeyService.getStoreProductPrice(skuid));
        }
        return redisCacheKeyList;
    }

 

标签:缓存,return,String,cache,redis,private,key,public,store
From: https://www.cnblogs.com/niun/p/17407914.html

相关文章

  • 低版本docker在dockerfile构建时的NO_PUBKEY问题
     问题我在ubuntu22.04的容器里面运行aptupdate的时候出现了以下报错[root@VM-16-9-centosdocker-kubuntu]#dockerrun--rm-itubuntu:22.04bashroot@8ac245b487e6:/#aptupdateGet:1http://security.ubuntu.com/ubuntujammy-securityInRelease[110kB]Get:2......
  • Redis Cluster两slave节点处理
    背景系统:CentOS7.6RedisClusterIP端口角色192.168.100.116380Master192.168.100.116381slave192.168.100.126380Master192.168.100.126381Slave192.168.100.136380Master192.168.100.136381Slave 因为某种原因导致(192.168.100.12)操......
  • 利用redis实现 分布式锁
    利用redis实现分布式锁 1.给需要添加锁的地方添加锁@GetMapping("/get")publicStringtest(HttpServletRequestrequest)throwsInterruptedException{System.out.println("begintodo");StringrequestId=request.getSession().get......
  • 最新Cobalt strike 4.8(专业版)([*] Generating X509 certificate and keystore (for SSL
    ColbaltStrike搭建和使用 下载: https://anonfiles.com/eay1D0rfzc/CobaltStrike4_8_lusuo_rar解压(如有)密码:lusuokali中: ┌──(root㉿kali)-[~]└─#unrarxCobaltStrike4_8_lusuo.rar    以kali为服务端打开 报错是因为没给可执行权限......
  • redis学习2通用命令--黑马
    key通用操作基本操作delkeyexistskeytypekey扩展操作为指定key设置有效期expirekeysecondspexpirekeymillisecondsexpireatkeytimestamppexpireatkeymilliseconds-timestamp获取key的有效时间(剩余时间)ttlkey(返回-2代表key已消失,返回-1表示存在key,返回其......
  • 保证数据库和缓存数据一致性
    1.修改数据接口开启事务2.修改数据接口中先修改DB,然后删除redis缓存3.如果删除redis抛异常,就回滚事务4.如果删除redis,redis没有返回结果,不确定是不是删除成功了,抛出异常,回滚事务5.后台界面可以查看数据库的值与缓存的值是否一致,界面有查看,修改数据的功能......
  • keyevent常用键列表
    常⽤键展示KEYCODE_CALL拨号键5KEYCODE_ENDCALL挂机键6KEYCODE_HOME按键Home3KEYCODE_MENU菜单键82KEYCODE_BACK返回键4KEYCODE_SEARCH搜索键84KEYCODE_CAMERA拍照键27KEYCODE_FOCUS拍照对焦键80KEYCODE_POWER电源键26KEYCODE_NOTIFICATION通知键83KEYCODE_M......
  • keyword模块
    1、介绍keyword.py是python关于关键字的一个模块。2、模块变量2.1kwlistkwlist=['False','None','True','__peg_parser__','and','as','assert','async',&......
  • Redis使用lua脚本实现库存扣减
    为什么使用Lua脚本为什么能合并多个原子操作?Redis官方文档:https://redis.io/docs/manual/programmability/eval-intro/ Redis保证脚本的原子执行。在执行脚本时,所有服务器活动在其整个运行期间都被阻止。这些语义意味着脚本的所有效果要么尚未发生,要么已经发生。脚本提供了......
  • uniapp APP内嵌 h5 解决web项目发布新版本需要清除浏览器缓存的问题
    1、新建index.html,写入禁止缓存的meta<!--设置meta不缓存--><metahttp-equiv="Expires"content="0"><metahttp-equiv="Pragma"content="no-cache"><metahttp-equiv="Cache-control"content="......