SpringCache Redis实现缓存@Cachealbe @CacheEvict

3 篇文章 0 订阅

Redis缓存实现.

pom文件
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.9.0</version>
		</dependency>
redis.properties配置文件
redis.host=127.0.0.1
# server port
redis.port=6379
# server pass
redis.pass=
# use dbIndex
redis.database=0
#max idel instance of jedis
redis.maxIdle=300
#if wait too long ,throw JedisConnectionException
redis.maxWait=3000
#if true,it will validate before borrow jedis instance,what you get instance is all usefull
redis.testOnBorrow=true
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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.2.xsd">
    <!-- 配置文件加载 -->
    <context:property-placeholder location="classpath:redis.properties"/>
    <!-- redis连接池redis.clients.jedis.JedisPoolConfig -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
    </bean>
    <!-- 连接工厂 -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>
    <!--序列化方式-->
    <!-- key的序列化方式-->
    <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    <!-- value的序列化方式-->
    <bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
    <!-- redis模板 -->
    <!--  在此处配置redis的序列化方式 key使用stringRedisSerializer序列化  value 使用jdkSerializationRedisSerializer 可以根据自己项目的情况去使用其他序列化方式-->
    <bean id="template" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
        <property name="keySerializer" ref="stringRedisSerializer"/>
        <property name="hashKeySerializer" ref="stringRedisSerializer"/>
        <property name="valueSerializer" ref="jdkSerializationRedisSerializer"/>
        <property name="hashValueSerializer" ref="jdkSerializationRedisSerializer"/>
    </bean>
    <!-- spring自己的缓存管理器,这里定义了缓存位置名称 ,即注解中的value -->
    <bean id="cacheManager"  class="org.springframework.cache.support.SimpleCacheManager">
        <property name="caches">
            <set>
                <!-- value名称要在类或方法的注解中使用 expiredTime过期时间  -->
                <bean class="cn.service.cache.redisCache.RedisCache">
                    <property name="redisTemplate" ref="template"/>
                    <property name="name" value="userCache"/>
                    <property name="expiredTime" value="1800"/>
                </bean>
                <bean class="cn.service.cache.RedisCache">
                    <property name="redisTemplate" ref="template"/>
                    <property name="name" value="studentCache"/>
                    <property name="expiredTime" value="1800"/>
                </bean>
                <bean class="cn.service.cache.RedisCache">
                    <property name="redisTemplate" ref="template"/>
                    <property name="name" value="teacherCache"/>
                    <property name="expiredTime" value="1800"/>
                </bean>
             
            </set>
        </property>
    </bean>
</beans>

value的属性和在代码中使用的注解值相同

<property name="name" value="teacherCache"/> 	
// 示例:
    @Cacheable(value = "teacherCache", key = "#id+'findById'")
    public List<Map> findCompanyChartById(Long id) {
		xxxxxxx.......
		}

RedisCache 是在java中编写的集成SpringCache的实现
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 描述
 */
public class RedisCache implements Cache {

    private static Logger logger = LoggerFactory.getLogger(RedisCache.class);

    /**
     * 前缀拼接公司id 例:companyId999
     */
    public static final String COMPANY_PREFIX = "xxxxxx";

    private RedisTemplate<String, Object> redisTemplate;

    /**
     * name属性为配置文件中指定的注解中的值
     */
    private String name;

    /**
     * 过期时间 默认过期时间1800秒
     */
    private Long expiredTime;

    /**
     * 拼接redis缓存前缀
     *
     * @return redisCachePrefix
     */
    public String getCompanyRedisCachePrefix(String key) {
        StringBuilder companyRedisPrefix = new StringBuilder();
        Long companyId = UserUtil.getCompanyId();
        companyRedisPrefix.append(COMPANY_PREFIX).append(companyId).append(":").append(name).append(":").append(key);
        return companyRedisPrefix.toString();
    }

    /**
     * 注解 @CacheEvict 当allEntries = true 会执行此方法, 会清空redis中所有缓存
     * 重新编写清空缓存方法
     */
    @Override
    public void clear() {
        logger.info("-------清理所有缓存(修改为清空当前公司缓存)------");
        /* stringRedisTemplate.execute((RedisCallback<String>) connection -> {
            connection.flushDb();
            return "ok";
        });*/
        clearRedisCache();

    }

    /**
     * key并不是@CacheEvict 中的value name属性才是
     *
     * @param key   CacheEvict中的key属性
     */
    @Override
    public void evict(Object key) {
        logger.info("-----根据value删除缓存-----");

        // 通配符清空公司内部对应键缓存
        clearRedisCache();
    }

    /**
     * 抽取清理缓存方法,当执行clear时默认清空当前公司,不清空所有
     */
    private void clearRedisCache() {
        String redisCacheKey = getCompanyRedisCachePrefix("*");
        Set<String> keys = redisTemplate.keys(redisCacheKey);
        // 清空userCache下的所有缓存(当前公司内)
        if (keys != null) {
            redisTemplate.delete(keys);
        }
    }

   
    @Override
    public ValueWrapper get(Object key) {
        logger.info("------缓存获取-------{}", key.toString());
        Long companyId = UserUtil.getCompanyId();
        if (companyId.equals(0L)) {
            return null;
        }
        // 拼接完整缓存名称
        String redisCacheKey = getCompanyRedisCachePrefix(key.toString());
        Object object = redisTemplate.opsForValue().get(redisCacheKey);
        ValueWrapper obj = (object != null ? new SimpleValueWrapper(object) : null);
        logger.info("------获取到内容-------{}", obj);
        return obj;
    }

    @Override
    public void put(Object key, Object value) {
        if (value == null) {
            return;
        }
        Long companyId = UserUtil.getCompanyId();
        if (companyId.equals(0L)) {
            return;
        }
        logger.info("-------加入缓存------");
        logger.info("key====={},value====={}", key, value);
        // 手动拼接缓存键名
        String redisCacheKey = getCompanyRedisCachePrefix(key.toString());
        // 过期时间
        final long liveTime = getExpiredTime();
        redisTemplate.opsForValue().set(redisCacheKey, value, liveTime, TimeUnit.SECONDS);
    }

    @Override
    public <T> T get(Object arg0, Class<T> arg1) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <T> T get(Object key, Callable<T> valueLoader) {
        return null;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public Object getNativeCache() {
        return this.redisTemplate;
    }

    @Override
    public ValueWrapper putIfAbsent(Object arg0, Object arg1) {
        return null;
    }

    public RedisTemplate<String, Object> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getExpiredTime() {
        if (expiredTime == null) {
            // 默认过期时间1800秒
            return 1800L;
        }
        return expiredTime;
    }

    public void setExpiredTime(Long expiredTime) {
        this.expiredTime = expiredTime;
    }

}

具体细节日后再进行补充

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值