Java those things

Redis 缓存使用(使用代理设计模式)

2019-07-01  本文已影响0人  M_ENG

Redis 缓存接口

package com.ec.biz.serv.redis.handler;

/**
 * Redis缓存 需要的数据查询接口
 *
 * @author MENG
 * @version 2019/6/21
 * @see
 */
public interface RedisCacheData
{
    /**
     * 分页查询 需缓存的数据
     *
     * @return
     */
    Object findDataByPage();
}

Redis 缓存接口实现

package com.ec.biz.serv.redis_handler.cache_data_impl;

import com.ec.biz.serv.dto.FreeCoupon;
import com.ec.biz.serv.dto.FreeCouponStoreRelation;
import com.ec.biz.serv.dto.UserFreeCoupon;
import com.ec.biz.serv.dto.interface_param.GetUserCouponParam;
import com.ec.biz.serv.dto.interface_return.UserFreeCouponReturn;
import com.ec.biz.serv.redis.RedisOperationUtil;
import com.ec.biz.serv.redis.handler.RedisCacheData;
import com.ec.biz.serv.redis.handler.RedisEnum;
import com.ec.biz.serv.repository.FreeCouponRepository;
import com.ec.biz.serv.repository.UserFreeCouponRepository;
import com.ec.biz.serv.util.SpringContextUtils;
import com.ec.biz.serv.util.validate.vali_util.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;


/**
 * ${DESCRIPTION}
 *
 * @author MENG
 * @version 2019/6/21
 * @see
 */
public class GetUserFreeCouponListRedisCacheDataImpl implements RedisCacheData,Runnable
{
    /**
     * 第一次更新缓存  默认缓存条数
     */
    private int pageSize = RedisEnum.USER_FREE_COUPON.getKeyCount();

    /**
     * 逻辑中需要使用的参数
     */
    private GetUserCouponParam getUserCouponParam;

    public void setGetUserCouponParam(GetUserCouponParam getUserCouponParam)
    {
        this.getUserCouponParam = getUserCouponParam;
    }

    /**
     * 用户优惠券
     */
    @Autowired
    private UserFreeCouponRepository userFreeCouponRepository = (UserFreeCouponRepository)SpringContextUtils.getBean("userFreeCouponRepository");

    /**
     * 优惠券
     */
    @Autowired
    private FreeCouponRepository freeCouponRepository = (FreeCouponRepository)SpringContextUtils.getBean("freeCouponRepository");

    @Override
    public Object findDataByPage()
    {
        //返回查询的数据
        // 查询数据库需要缓存的数据  
        return pageResult;
    }


    public static void clearRedisCache(String appId,String userId)
    {
        //清除Redis相关的缓存  appId和userId 是查询条件 必填
        //userFreeCoupon:#{appId}:#{userId}
        String keyPrefix = RedisEnum.USER_FREE_COUPON.getKeyPrefix();

        keyPrefix = keyPrefix.replace("#{appId}",appId);

        keyPrefix = keyPrefix.replace("#{userId}",userId);

        RedisOperationUtil.deleteKeyRedisCache(keyPrefix);

        //默认缓存
        GetUserFreeCouponListRedisCacheDataImpl getUserFreeCouponListRedisCacheData = new GetUserFreeCouponListRedisCacheDataImpl();

        GetUserCouponParam getUserCouponParam = new GetUserCouponParam();

        getUserCouponParam.setAppId(appId);

        getUserCouponParam.setUserId(userId);

        getUserFreeCouponListRedisCacheData.setGetUserCouponParam(getUserCouponParam);

        Thread thread = new Thread(getUserFreeCouponListRedisCacheData);

        thread.start();
    }

    public static Object getRedisCache(GetUserCouponParam getUserCouponParam)
    {
        //设置UserCouponParam key
        String redisKey = RedisEnum.USER_FREE_COUPON.getKeyRule();

        //userFreeCoupon:#{appId}:#{userId}:#{pageNo}:#{pageSize}:#{storeId}
        redisKey = redisKey.replace("#{appId}",getUserCouponParam.getAppId());

        redisKey = redisKey.replace("#{userId}",getUserCouponParam.getUserId());

        redisKey = redisKey.replace("#{pageNo}",getUserCouponParam.getPageNo() == null ? "1" : getUserCouponParam.getPageNo());

        redisKey = redisKey.replace("#{pageSize}",getUserCouponParam.getPageSize() == null ? String.valueOf(RedisEnum.USER_FREE_COUPON.getKeyCount()) : getUserCouponParam.getPageSize());

        redisKey = redisKey.replace("#{storeId}",getUserCouponParam.getStoreId() == null ? "" : getUserCouponParam.getStoreId());

        GetUserFreeCouponListRedisCacheDataImpl getUserFreeCouponListRedisCacheData = new GetUserFreeCouponListRedisCacheDataImpl();

        getUserFreeCouponListRedisCacheData.setGetUserCouponParam(getUserCouponParam);

        Object object = RedisOperationUtil.getValueRedisCache(redisKey);

        if(object == null)
        {
            object = getUserFreeCouponListRedisCacheData.findDataByPage();
        }

        RedisOperationUtil.setValueRedisCache(redisKey,object);

        return object;
    }

    @Override
    public void run()
    {
        getRedisCache(this.getUserCouponParam);
    }
}

Redis 工具类

package com.ec.biz.serv.redis;

import com.ec.biz.serv.util.SpringContextUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;


/**
 * redis 操作工具类
 *
 * @author MENG
 * @version 2019/6/21
 * @see
 */
public class RedisOperationUtil
{

    private static final int cacheTime = 24;//hours

    /**
     * 返回 对应的key缓存业务处理过的数据
     *
     *
     * @param key
     * @return
     */
    public static Object getValueRedisCache(String key)
    {
        RedisTemplate<String,Object> redisTemplate = (RedisTemplate<String, Object>)SpringContextUtils.getBean("redisTemplate");

        ValueOperations valueOperations = redisTemplate.opsForValue();
        //
        Object objectValue = valueOperations.get(key);

        if(objectValue == null)
        {
            return null;
        }

        return objectValue;
    }

    public static void setValueRedisCache(String key,Object objectValue)
    {
        RedisTemplate<String,Object> redisTemplate = (RedisTemplate<String, Object>)SpringContextUtils.getBean("redisTemplate");

        ValueOperations valueOperations = redisTemplate.opsForValue();

        //查询数据 存到Redis
        valueOperations.set(key,objectValue,cacheTime, TimeUnit.HOURS);
    }

    /**
     * 删除 对应的模糊key 并缓存默认的数据
     *
     *
     * @param key
     * @return
     */
    public static void deleteKeyRedisCache(String key)
    {
        StringRedisTemplate redisTemplate = (StringRedisTemplate)SpringContextUtils.getBean("stringRedisTemplate");

        System.out.println("key : " + key);

        System.out.println(redisTemplate.keys(key + "*"));

        redisTemplate.delete(redisTemplate.keys(key + "*"));
    }
}

Redis 配置

package com.ec.biz.serv.redis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * ${DESCRIPTION}
 *
 * @author MENG
 * @version 2019/6/20
 * @see
 */
@Configuration
public class RedisConfiguration extends CachingConfigurerSupport
{
    /**
     *
     * spring提供两个类操作Redis RedisTemplate(操作对象) StringRedisTemplate(操作String)
     *
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory)
    {
        RedisTemplate template = new StringRedisTemplate(factory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();

        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(om);

        RedisSerializer<String> redisSerializer = new StringRedisSerializer();//Long类型不可以会出现异常信息;

        template.setKeySerializer(redisSerializer);

        template.setValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();

        template.setEnableTransactionSupport(true);

        return template;
    }
}

Redis 枚举

package com.ec.biz.serv.redis.handler;

/**
 * ${DESCRIPTION}
 *
 * @author MENG
 * @version 2019/6/21
 * @see
 */
public enum RedisEnum
{
    USER_FREE_COUPON("userFreeCoupon:#{appId}:#{userId}","userFreeCoupon:#{appId}:#{userId}:#{pageNo}:#{pageSize}:#{storeId}",10);

    RedisEnum(String keyPrefix,String keyRule,int keyCount)
    {
        this.keyPrefix = keyPrefix;

        this.keyRule = keyRule;

        this.keyCount = keyCount;
    }

    /**
     * 删除 key
     */
    private String keyPrefix;

    public String getKeyPrefix()
    {
        return this.keyPrefix;
    }

    /**
     * 根据查询条件拼接KEY
     * Redis key = keyPrefix + ":" + 条件
     *
     */
    private String keyRule;

    public String getKeyRule()
    {
        return this.keyRule;
    }

    /**
     * 默认缓存条数
     */
    private int keyCount;

    public int getKeyCount()
    {
        return this.keyCount;
    }
}

上一篇下一篇

猜你喜欢

热点阅读