【Spring】SSM框架配置Redis进行缓存

版权声明:如有转载请标明出处https://blog.csdn.net/Evan_QB https://blog.csdn.net/Evan_QB/article/details/82622755

此过程是在SSM框架搭建完毕之后进行的扩展

首先引入redis依赖:

<!-- redis -->
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.8.1</version>
  <type>jar</type>
</dependency>

准备对应的数据源redis.properties

#redis缓存配置
redis.host=127.0.0.1
redis.port=6379
redis.pass=密码
redis.database=2
redis.timeout=3000

#redis连接池配置
redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true
redis.connectionTimeout=5000

使用redis.xml加载数据源

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!--加载redis.properties-->
    <context:property-placeholder location="classpath:redis.properties" />

    <!--配置redis数据源-->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" >
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxTotal" value="${redis.maxActive}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>

    <!--配置ShardJedisPool-->
    <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" scope="singleton">
        <constructor-arg index="0" ref="jedisPoolConfig" />
        <constructor-arg index="1">
            <list>
                <bean class="redis.clients.jedis.JedisShardInfo">
                    <constructor-arg name="host" value="${redis.host}" />
                    <constructor-arg name="port" value="${redis.port}"/>
                    <constructor-arg name="timeout" value="${redis.timeout}"/>
                    <property name="password" value="${redis.pass}" />
                    <property name="connectionTimeout" value="${redis.connectionTimeout}"/>
                </bean>
            </list>
        </constructor-arg>
    </bean>

</beans>

在applicationContext.xml中引入redis.xml

<!--引入redis.xml-->
<import resource="redis.xml" />

在service层配置ShardedJedisPool连接池

@Service("redisPool")
@Slf4j
public class RedisPool {
    @Resource(name = "shardedJedisPool")
    private ShardedJedisPool shardedJedisPool;

    /**
     * 创建实例
     * @return
     */
    public ShardedJedis instance(){
        return shardedJedisPool.getResource();
    }

    /**
     * 安全关闭
     * @param shardedJedis
     */
    public void safeClose(ShardedJedis shardedJedis){
        try {
            if (shardedJedis != null){
                shardedJedis.close();
            }
        }catch (Exception e){
            log.error("return redis resource exception",e);
        }
    }

}

编写进行缓存、获取缓存、生成缓存key的方法

/**
 * @author evan_qb
 * @date 2018/9/11
 */
@Service
@Slf4j
public class SysCacheService {
    @Resource(name = "redisPool")
    private RedisPool redisPool;

    /**
     * 调用缓存
     * @param toSaveValue
     * @param timeoutSeconds
     * @param prefix
     */
    public void saveCache(String toSaveValue, int timeoutSeconds, CacheKeyConstants prefix){
        saveCache(toSaveValue,timeoutSeconds,prefix,null);
    }

    /**
     * 进行缓存
     * @param toSaveValue
     * @param timeoutSeconds
     * @param prefix
     * @param keys
     */
    public void saveCache(String toSaveValue, int timeoutSeconds, CacheKeyConstants prefix,String... keys){
        if (toSaveValue == null){
            return;
        }
        ShardedJedis shardedJedis = null;
        try {
            String cacheKey = generateCacheKey(prefix,keys);
            shardedJedis = redisPool.instance();
            shardedJedis.setex(cacheKey,timeoutSeconds,toSaveValue);
        }catch (Exception e){
            log.error("save cache exception,prefix:{},keys:{}",prefix.name(),JsonMapper.object2String(keys),e);
        }finally {
            redisPool.safeClose(shardedJedis);
        }
    }

    /**
     * 获取缓存
     * @param prefix
     * @param keys
     * @return
     */
    public String getFromCache(CacheKeyConstants prefix,String... keys){
        ShardedJedis shardedJedis = null;
        String cacheKey = generateCacheKey(prefix,keys);
        try {
            shardedJedis = redisPool.instance();
            String value = shardedJedis.get(cacheKey);
            return value;
        }catch (Exception e){
            log.error("get from cache exception,prefix:{},keys:{}",prefix.name(),JsonMapper.object2String(keys),e);
            return null;
        }finally {
            redisPool.safeClose(shardedJedis);
        }
    }


    /**
     * 生成缓存的key
     * @param prefix
     * @param keys
     * @return
     */
    private String generateCacheKey(CacheKeyConstants prefix,String... keys){
        String key = prefix.name();
        if (keys != null && keys.length > 0){
            key += "_" + Joiner.on("_").join(keys);
        }
        return key;
    }
}

定义缓存常用的key常量前缀

/**
 * @author evan_qb
 * @date 2018/9/11
 * 缓存常量
 */
@Getter
public enum  CacheKeyConstants {
    SYSTEM_ACLS,
    USER_ACLS
}

对缓存场景进行分析,找出需要缓存的数据

编写代码将其进行缓存

扫描二维码关注公众号,回复: 3495811 查看本文章
/**
 * 对当前用户对应的权限列表进行缓存
 * @return
 */
public List<SysAcl> getCurrentUserAclListFromCache(){
    int userId = RequestHolder.getCurrentUser().getId();
    String cacheValue = sysCacheService.getFromCache(CacheKeyConstants.USER_ACLS,String.valueOf(userId));
    if (StringUtils.isBlank(cacheValue)){
        List<SysAcl> aclList = getCurrentuserAclList();
        if (CollectionUtils.isNotEmpty(aclList)){
            sysCacheService.saveCache(JsonMapper.object2String(aclList),600,
                    CacheKeyConstants.USER_ACLS,String.valueOf(userId));
        }
        return aclList;
    }
    return JsonMapper.string2Object(cacheValue, new TypeReference<List<SysAcl>>() {});
}

调用缓存的方法

接下来进行测试:

第一次进入发现redis中没有缓存,先对其进行缓存,然后将结果返回

第二次进入方法,先查询redis中是否有缓存,如果有,则直接取出数据,进行返回

猜你喜欢

转载自blog.csdn.net/Evan_QB/article/details/82622755
今日推荐