其他分享
首页 > 其他分享> > JetCache配置

JetCache配置

作者:互联网

一. 依赖

<!--依赖-->
<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>

 

二.  JetCache - Redis配置

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;
    }
}

 

三.  使用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

 

标签:JetCache,配置,alibaba,jetcache,alicp,import,com,public
来源: https://www.cnblogs.com/wftop1/p/14770132.html