springBoot2 下配置springCache redis 缓存配置及使用

学习内容:

springCache + redis 缓存
例如:
1、 springBoot2 配置springCache + redis 缓存生存周期 + 配置redis 序列化方式 Json
2、 配置SpringCache Key自定义Key
3 springCache 注解使用
下篇学习:

1、 统一配置springCache 缓存redis expireTIme yml配置 及如何定制个性化时间
2 springCache 注解详细解答
3, 提供demo git 代码


学习时间:

提示:这里可以添加计划学习的时间
例如:
1、 周一至周五晚上 7 点—晚上9点
2、 周六上午 9 点-上午 11 点
3、 周日下午 3 点-下午 6 点


学习产出:

1、 springBoot2 配置springCache + redis 缓存生存周期

springBoot2

MainApplication.java

import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;

import com.dtflys.forest.springboot.annotation.ForestScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@EnableCaching //开启基于注解的缓存
@EnableScheduling // 开启定时任务
  
public class MainApplication {
    private static final Logger logger = LoggerFactory.getLogger(MainApplication.class);
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
        logger.info("---------------------project started!!!-----------------------");
    }

springCache CacheMange config + reids

RedisConfig.java

package cn.xxxxx.config;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;

/**
* @author Alpha丶X
* @version 1.0.0
* @Description: redis缓存配置类
*
* <p>创建时间:2020年12月16日 19:38</p>
*/
@Configuration
public class RedisConfig {

   @Primary
   @Bean(name = "redisTemplate")
   public RedisTemplate getRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
       ObjectMapper objectMapper = new ObjectMapper();
       objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
       objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
       GenericJackson2JsonRedisSerializer json2java = new GenericJackson2JsonRedisSerializer(objectMapper);
       RedisTemplate redisTemplate = new RedisTemplate();
       redisTemplate.setConnectionFactory(redisConnectionFactory);
       redisTemplate.setKeySerializer(new StringRedisSerializer());
       redisTemplate.setValueSerializer(json2java);
       redisTemplate.setHashKeySerializer(new StringRedisSerializer());
       redisTemplate.setHashValueSerializer(json2java);
       return redisTemplate;
   }


   // 设置缓存过期时间为一天  缓存 10分钟
   // 禁用缓存空值,不缓存null校验
   @Bean
   @Primary
   public RedisCacheManager employeeRedisCacheManager(RedisConnectionFactory redisConnectionFactory) {
       RedisCacheConfiguration cacheConfiguration =
               RedisCacheConfiguration.defaultCacheConfig()
                       .entryTtl(Duration.ofSeconds(1200))    //缓存时间
                  //     .computePrefixWith(cacheName -> "rubik" + cacheName)
                       .disableCachingNullValues()
                       .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new
                               GenericJackson2JsonRedisSerializer()));
       // 设置CacheManager的值序列化方式为json序列化,可加入@Class属性
       return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(cacheConfiguration).build();
       // 设置默认的cache组件
   }
}

2、 配置SpringCache Key自定义Key

SimpleSpringCacheKeyGenerator

package cn.XXXXX.config;

import cn.XXXXX.common.constants.model.DefaultDBValue;
import com.alibaba.fastjson.JSON;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKey;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 *
 */
@Configuration
@Component("simpleSpringCacheKeyGenerator")
@Primary
public class SimpleSpringCacheKeyGenerator implements KeyGenerator {
    public SimpleSpringCacheKeyGenerator() {
    }

    @Override
    public Object generate(Object target, Method method, Object... params) {

        return generateKey(target,method, params);
    }

    public static Object generateKey(Object target,Method method, Object... params) {

        StringBuilder strb = new StringBuilder();
        if (method != null && method.getDeclaringClass() != null) {
            strb.append(method.getDeclaringClass().getName()).append(DefaultDBValue.COLON).append(method.getName());
        }
        strb.append(DefaultDBValue.COLON).append(generateParamKey(params));
        return strb.toString();
    }


    public static Object generateParamKey(Object... params) {
        if (params.length == 0) {
            return SimpleKey.EMPTY;
        } else {
            if (params.length == 1) {
                Object param = params[0];
                if (param != null && !param.getClass().isArray()) {
                    return param;
                }
            }
            StringBuilder sb = new StringBuilder();
            for (Object obj : params) {
                if (obj != null){
                    sb.append(obj.getClass().getName());
                    sb.append("[");
                    sb.append(JSON.toJSONString(obj));
                    sb.append("]:");
                }
            }

            return sb.toString();
        }
    }
}

3 springCache 注解使用

// 清理缓存块 
   @Override
   @CacheEvict(value = RIK_NEW_UIFLOW_UI_CONFIG, allEntries = true)
   public UcUiFlow deleteUcUiFlow(String ucUiFlowId) {
       UcUiFlow tUiFlow = new UcUiFlow();
       tUiFlow.setUcUiFlowId(ucUiFlowId);
       tUiFlow.setModifiedon(new Date());
       tUiFlow.setModifiedby(UserLoginHandler.getLoginName());
       tUiFlow.setDeletionState(DefaultDBValue.DELETION_STATE_DEL);
       ucUiFlowMapper.updateByPrimaryKeySelective(tUiFlow);
       return getUcUiFlowByUcUiFlowId(tUiFlow.getUcUiFlowId());
   } 

缓存数据


    @Override
    @Cacheable(value = RIK_NEW_UIFLOW_UI_CONFIG, keyGenerator = "simpleSpringCacheKeyGenerator")

    public PageHelpShow<UcUiFlow> getUcUiFlowByPhIdAndUseTypePageList(String platformHospitalId,
                                                                      String useType,
                                                                      int page,
                                                                      int size) {


        Example example = new Example(UcUiFlow.class);
        example.setOrderByClause("createdon asc");
        example.createCriteria().andEqualTo("platformHospitalId", platformHospitalId).andEqualTo("useType", useType)
                .andEqualTo("deletionState", DefaultDBValue.CREATE_DELETION_STATE);
        PageHelper.startPage(page, size);
        List<UcUiFlow> ucUiFlowList = ucUiFlowMapper.selectByExample(example);


        UcUiFlow uiFlow = new UcUiFlow();
        uiFlow.setPlatformHospitalId(platformHospitalId);
        uiFlow.setUseType(useType);
        uiFlow.setDeletionState(DefaultDBValue.CREATE_DELETION_STATE);
        List<UcUiFlow> ucUiFlowListCount = ucUiFlowMapper.select(uiFlow);

        PageHelpShow result = new PageHelpShow<>();
        result.setTotalCount(ucUiFlowListCount.size());
        PageInfo<UcUiFlow> info = new PageInfo(ucUiFlowListCount, size);
        result.setPageSize(size);
        if (org.springframework.util.CollectionUtils.isEmpty(ucUiFlowList)) {
            return result;
        }


        for (UcUiFlow tUiFlow : ucUiFlowList) {
            List<String> keys = new ArrayList<>();
            String definitionJSON = FlowDefinationFormattor.getJsonStr(tUiFlow.getDefinition(), tUiFlow.getDefineZone());
            tUiFlow.setDefinitionJSON(definitionJSON);
            JSONArray array = JSONArray.fromObject(definitionJSON);
            for (Object object : array) {
                if (JSONObject.fromObject(object).get("vId") != null && JSONObject.fromObject(object).get("vId").toString().contains("F_1-")) {
                    keys.add(StringUtils.substring(JSONObject.fromObject(object).get("vId").toString(), 2));
                }
            }
            //    tUiFlow.setPreUrl(pjWechatUrl(useType,  platformHospitalId));
            //     tUiFlow.setStepList(keys.toString());
        }

        result.setList(ucUiFlowList);
        result.setCurrentPage(page);
        result.setTotalPage((int) info.getTotal() / size + 1);
        result.setTotalCount(info.getTotal());

        return result;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值