Loading

JetCache+SpringMvc配置

Jedis

  • 依赖
<!--依赖-->
<properties>
    <jetcache.version>2.5.14</jetcache.version>
</properties>

<dependency>
    <groupId>com.alicp.jetcache</groupId>
    <artifactId>jetcache-anno</artifactId>
    <version>${jetcache.version}</version>
</dependency>
<dependency>
    <groupId>com.alicp.jetcache</groupId>
    <artifactId>jetcache-redis</artifactId>
    <version>${jetcache.version}</version>
</dependency>

<!--因为Jetcache适配jedis版本为2.9.0, jedis 2.9.0适配spring-data-redis 1.8.0.RELEASE-->
<properties>
    <jedis.version>2.9.0</jedis.version>
    <spring-data-redis.version>1.8.0.RELEASE</spring-data-redis.version>
</properties>

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>${spring-data-redis.version}</version>
</dependency>
  • xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
       xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
    <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
    <!-- <cache:annotation-driven cache-manager="cacheManager" />-->
    <!-- redis 相关配置 -->
    <bean id="redisSentinelConfiguration"
          class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
        <property name="master">
            <bean class="org.springframework.data.redis.connection.RedisNode">
                <property name="name" value="${redis.cluster.name}"></property>
            </bean>
        </property>
        <property name="sentinels">
            <set>
                <bean class="org.springframework.data.redis.connection.RedisNode">
                    <constructor-arg index="0" value="${redis.sentinels_1.host}" />
                    <constructor-arg index="1" value="${redis.sentinels_1.port}"/>
                </bean>
                <bean class="org.springframework.data.redis.connection.RedisNode">
                    <constructor-arg index="0" value="${redis.sentinels_2.host}"/>
                    <constructor-arg index="1" value="${redis.sentinels_2.port}"/>
                </bean>
                <bean class="org.springframework.data.redis.connection.RedisNode">
                    <constructor-arg index="0" value="${redis.sentinels_3.host}"/>
                    <constructor-arg index="1" value="${redis.sentinels_3.port}"/>
                </bean>
            </set>
        </property>
    </bean>
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="100"/>
        <property name="maxTotal" value="4000"/>
        <property name="testOnBorrow" value="true"/>
    </bean>
    <bean id="jedisConnectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="password" value="${redis.connection.password}"/>
        <property name="usePool" value="true"/>
        <property name="database" value="${redis.dbIndex}"/>
        <property name="poolConfig" ref="jedisPoolConfig"></property>
        <constructor-arg ref="redisSentinelConfiguration" />
    </bean>
    <bean id="stringRedisSerializer"  class="org.springframework.data.redis.serializer.StringRedisSerializer" />
    <bean id="fastJsonRedisSerializer" class="com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer"/>
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
        <property name="keySerializer" ref="stringRedisSerializer" />
        <property name="hashKeySerializer" ref="stringRedisSerializer" />
        <property name="hashValueSerializer" ref="fastJsonRedisSerializer" />
        <property name="valueSerializer" ref="stringRedisSerializer"/>
    </bean>
</beans>
  • Bean配置
package com.wf.fire.config;

import com.alicp.jetcache.anno.CacheConsts;
import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import com.alicp.jetcache.anno.config.EnableMethodCache;
import com.alicp.jetcache.anno.support.GlobalCacheConfig;
import com.alicp.jetcache.anno.support.SpringConfigProvider;
import com.alicp.jetcache.embedded.EmbeddedCacheBuilder;
import com.alicp.jetcache.embedded.LinkedHashMapCacheBuilder;
import com.alicp.jetcache.redis.RedisCacheBuilder;
import com.alicp.jetcache.support.FastjsonKeyConvertor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.util.Pool;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wf
 * @date 2021年04月28日 18:04
 * @description Jetcache sentinal版配置
 */
@Configuration
@EnableMethodCache(basePackages = "com.wf")
@EnableCreateCacheAnnotation
public class JetCacheConfig {

    @Autowired
    private RedisSentinelConfiguration redisSentinelConfiguration;

    @Autowired
    private JedisPoolConfig jedisPoolConfig;

    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    public Pool<Jedis> pool() {
        Set<String> collect = redisSentinelConfiguration.getSentinels().stream().map(m -> (m.getHost() + ":" + m.getPort())).collect(Collectors.toSet());
        return new JedisSentinelPool(redisSentinelConfiguration.getMaster().getName(), collect, jedisPoolConfig, jedisConnectionFactory.getPassword());
    }

    @Bean
    public SpringConfigProvider springConfigProvider() {
        return new SpringConfigProvider();
    }
    
    @Bean
    public GlobalCacheConfig config(SpringConfigProvider configProvider) {
        Map localBuilders = new HashMap();
        EmbeddedCacheBuilder localBuilder = LinkedHashMapCacheBuilder
                .createLinkedHashMapCacheBuilder()
                .keyConvertor(FastjsonKeyConvertor.INSTANCE);
        localBuilders.put(CacheConsts.DEFAULT_AREA, localBuilder);

        Map remoteBuilders = new HashMap();
        RedisCacheBuilder remoteCacheBuilder = RedisCacheBuilder.createRedisCacheBuilder()
                .keyConvertor(FastjsonKeyConvertor.INSTANCE)
                .valueEncoder(FastjsonValueEncoder.INSTANCE)
                .valueDecoder(FastjsonValueDecoder.INSTANCE)
                .jedisPool(pool());
        remoteBuilders.put(CacheConsts.DEFAULT_AREA, remoteCacheBuilder);
        GlobalCacheConfig globalCacheConfig = new GlobalCacheConfig();
        globalCacheConfig.setConfigProvider(configProvider);
        globalCacheConfig.setLocalCacheBuilders(localBuilders);
        globalCacheConfig.setRemoteCacheBuilders(remoteBuilders);
        globalCacheConfig.setStatIntervalMinutes(15);
        globalCacheConfig.setAreaInCacheName(false);
        return globalCacheConfig;
    }
}


Lettuce

  • 依赖
<!--依赖-->
<properties>
    <jetcache.version>2.5.14</jetcache.version>
</properties>

<dependency>
    <groupId>com.alicp.jetcache</groupId>
    <artifactId>jetcache-anno</artifactId>
    <version>${jetcache.version}</version>
</dependency>

<dependency>
    <groupId>com.alicp.jetcache</groupId>
    <artifactId>jetcache-redis-lettuce</artifactId>
    <version>${jetcache.version}</version>
</dependency>

<!--因为Jetcache适配jedis版本为2.9.0, jedis 2.9.0适配spring-data-redis 1.8.0.RELEASE-->
<properties>
    <jedis.version>2.9.0</jedis.version>
    <spring-data-redis.version>1.8.0.RELEASE</spring-data-redis.version>
</properties>

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>${spring-data-redis.version}</version>
</dependency>

<dependency>
    <groupId>biz.paluch.redis</groupId>
    <artifactId>lettuce</artifactId>
    <version>4.2.2.Final</version>
</dependency>
  • xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
       xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
    <bean id="redisSentinelConfiguration"
          class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
        <property name="master">
            <bean class="org.springframework.data.redis.connection.RedisNode">
                <property name="name" value="${redis.cluster.name}"></property>
            </bean>
        </property>
        <property name="sentinels">
            <set>
                <bean class="org.springframework.data.redis.connection.RedisNode">
                    <constructor-arg index="0" value="${redis.sentinels_1.host}"/>
                    <constructor-arg index="1" value="${redis.sentinels_1.port}"/>
                </bean>
                <bean class="org.springframework.data.redis.connection.RedisNode">
                    <constructor-arg index="0" value="${redis.sentinels_2.host}"/>
                    <constructor-arg index="1" value="${redis.sentinels_2.port}"/>
                </bean>
                <bean class="org.springframework.data.redis.connection.RedisNode">
                    <constructor-arg index="0" value="${redis.sentinels_3.host}"/>
                    <constructor-arg index="1" value="${redis.sentinels_3.port}"/>
                </bean>
            </set>
        </property>
    </bean>

    <bean id="lettuceConnectionFactory"
          class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory">
        <constructor-arg name="sentinelConfiguration" ref="redisSentinelConfiguration"/>
        <property name="password" value="${redis.connection.password}"/>
    </bean>

    <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    <bean id="fastJsonRedisSerializer" class="com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer"/>
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="lettuceConnectionFactory"/>
        <property name="keySerializer" ref="stringRedisSerializer"/>
        <property name="hashKeySerializer" ref="stringRedisSerializer"/>
        <property name="hashValueSerializer" ref="fastJsonRedisSerializer"/>
        <property name="valueSerializer" ref="stringRedisSerializer"/>
    </bean>
</beans>
  • Bean配置
package com.wf.vqmp.config;

import com.alicp.jetcache.anno.CacheConsts;
import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import com.alicp.jetcache.anno.config.EnableMethodCache;
import com.alicp.jetcache.anno.support.GlobalCacheConfig;
import com.alicp.jetcache.anno.support.SpringConfigProvider;
import com.alicp.jetcache.embedded.EmbeddedCacheBuilder;
import com.alicp.jetcache.embedded.LinkedHashMapCacheBuilder;
import com.alicp.jetcache.redis.lettuce.RedisLettuceCacheBuilder;
import com.alicp.jetcache.support.FastjsonKeyConvertor;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableMethodCache(basePackages = "com.wf")
@EnableCreateCacheAnnotation
public class JetCacheConfig {

    @Autowired
    private LettuceConnectionFactory lettuceConnectionFactory;

    @Autowired
    private RedisSentinelConfiguration redisSentinelConfiguration;

    @Bean
    public RedisClient redisClient() {
        RedisNode redisNode = redisSentinelConfiguration.getSentinels().stream().findFirst().orElse(null);
        RedisURI sentinelUri = RedisURI.builder()
                .withSentinel(redisNode.getHost(), redisNode.getPort())
                .withSentinelMasterId(redisSentinelConfiguration.getMaster().getName())
                .withPassword(lettuceConnectionFactory.getPassword().toCharArray())
                .build();
        RedisClient client = RedisClient.create(sentinelUri);
        return client;
    }

    @Bean
    public SpringConfigProvider springConfigProvider() {
        return new SpringConfigProvider();
    }

    @Bean
    public GlobalCacheConfig config(SpringConfigProvider configProvider, RedisClient client) {
        Map localBuilders = new HashMap();
        EmbeddedCacheBuilder localBuilder = LinkedHashMapCacheBuilder
                .createLinkedHashMapCacheBuilder()
                .keyConvertor(FastjsonKeyConvertor.INSTANCE);
//                .expireAfterWrite(5000, TimeUnit.MILLISECONDS)
//                .expireAfterAccess(0, TimeUnit.MILLISECONDS);
        localBuilders.put(CacheConsts.DEFAULT_AREA, localBuilder);

        Map remoteBuilders = new HashMap();
        RedisLettuceCacheBuilder remoteCacheBuilder = RedisLettuceCacheBuilder.createRedisLettuceCacheBuilder();
        remoteCacheBuilder.setKeyConvertor(FastjsonKeyConvertor.INSTANCE);
        remoteCacheBuilder.setValueDecoder(FastjsonValueDecoder.INSTANCE);
        remoteCacheBuilder.setValueEncoder(FastjsonValueEncoder.INSTANCE);
        remoteCacheBuilder.setRedisClient(client);

        remoteBuilders.put(CacheConsts.DEFAULT_AREA, remoteCacheBuilder);
        GlobalCacheConfig globalCacheConfig = new GlobalCacheConfig();
        globalCacheConfig.setConfigProvider(configProvider);
        globalCacheConfig.setLocalCacheBuilders(localBuilders);
        globalCacheConfig.setRemoteCacheBuilders(remoteBuilders);
        globalCacheConfig.setStatIntervalMinutes(15);
        globalCacheConfig.setAreaInCacheName(false);
        return globalCacheConfig;
    }
}

使用FastJson来序列化、反序列化

package com.wf.fire.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alicp.jetcache.support.AbstractValueEncoder;
import com.alicp.jetcache.support.CacheEncodeException;

/**
 * Created on 2016/10/3. 序列化
 *
 * @author <a href="mailto:areyouok@gmail.com">huangli</a>
 */
public class FastjsonValueEncoder extends AbstractValueEncoder {

    @SuppressWarnings("deprecation")
    public static final FastjsonValueEncoder INSTANCE = new FastjsonValueEncoder(true);

    protected static int IDENTITY_NUMBER = 0x4A953A81;

    public FastjsonValueEncoder(boolean useIdentityNumber) {
        super(useIdentityNumber);
    }

    @Override
    public byte] apply(Object value) {
        try {
            byte] bs1 = JSON.toJSONBytes(value, SerializerFeature.WriteClassName);
            if (useIdentityNumber) {
                byte] bs2 = new bytebs1.length + 4];
                writeHeader(bs2, IDENTITY_NUMBER);
                System.arraycopy(bs1, 0, bs2, 4, bs1.length);
                return bs2;
            } else {
                return bs1;
            }
        } catch (Exception e) {
            StringBuilder sb = new StringBuilder("Fastjson Encode error. ");
            sb.append("msg=").append(e.getMessage());
            throw new CacheEncodeException(sb.toString(), e);
        }
    }
}
package com.wf.fire.config;

/**
 * @author wf
 * @date 2021年04月29日 14:43
 * @description 反序列化
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alicp.jetcache.support.AbstractValueDecoder;
import com.alicp.jetcache.support.DecoderMap;

/**
 * Created on 2016/10/4.
 * <p>
 * ParserConfig.getGlobalInstance().addAccept("com.company.yourpackage.");
 * DecoderMap.register(FastjsonValueEncoder.IDENTITY_NUMBER, FastjsonValueDecoder.INSTANCE);
 *
 * @author <a href="mailto:areyouok@gmail.com">huangli</a>
 */
public class FastjsonValueDecoder extends AbstractValueDecoder {

    @SuppressWarnings("deprecation")
    public static final FastjsonValueDecoder INSTANCE = new FastjsonValueDecoder(true);

    public FastjsonValueDecoder(boolean useIdentityNumber) {
        super(useIdentityNumber);
    }

    static {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        DecoderMap.register(FastjsonValueEncoder.IDENTITY_NUMBER, FastjsonValueDecoder.INSTANCE);
    }

    @Override
    public Object doApply(byte] buffer) {
        if (useIdentityNumber) {
            byte] bs = new bytebuffer.length - 4];
            System.arraycopy(buffer, 4, bs, 0, bs.length);
            return JSON.parse(bs);
        } else {
            return JSON.parse(buffer);
        }
    }
}

四. 使用到Interface的方法上

@Cached(name = "getMetrics" ,expire = 3600) 
List<MetricsVO> getMetrics(String sysCode, String empNum, String month);

参考 :

Jetcache配置
https://github.com/alibaba/jetcache/wiki/GettingStarted_CN
https://github.com/alibaba/jetcache/wiki/Config_CN

Jetcache API
https://github.com/alibaba/jetcache/wiki/CacheAPI_CN

Jetcache 注解使用
https://github.com/alibaba/jetcache/wiki/MethodCache_CN
https://github.com/alibaba/jetcache/wiki/CreateCache_CN

使用Fastjson 序列化反序列化
https://github.com/alibaba/jetcache/wiki/FAQ_CN

【解决 com.alibaba.fastjson.JSONException: autoType is not support.】
https://github.com/alibaba/fastjson/wiki/enable_autotype
https://www.cnblogs.com/lpob/p/11853592.html
https://blog.csdn.net/wgzhl2008/article/details/82184240
https://www.kanzhun.com/jiaocheng/169750.html

Lettuce配置

https://gist.github.com/yangl/a0cabe55c8bae8d9ad0fdf10ae17aec4

https://javamana.com/2022/123/202205030602006806.html

https://blog.csdn.net/FlyLikeButterfly/article/details/124496285

posted @ 2021-05-14 22:19  FynnWang  阅读(1110)  评论(0编辑  收藏  举报