redis缓存和spring cache的集成

作者: jsondream | 来源:发表于2016-03-16 14:18 被阅读9398次

pom.xml文件中加入依赖关系:

<dependency>   
    <groupId>org.springframework.data</groupId>   
    <artifactId>spring-data-redis</artifactId>   
    <version>1.6.0.RELEASE</version>   
</dependency>   
<dependency>   
    <groupId>redis.clients</groupId>   
    <artifactId>jedis</artifactId>   
    <version>2.7.3</version>   
</dependency> 

在项目中集成基础配置

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ResourceBundle;

/**
 * <p>
 *     spring cache和redis的结合配置类
 * </p>
 *
 * @author wangguangdong
 * @version 1.0
 * @Date 16/2/25
 * @see RedisCacheManager
 * @see JedisConnectionFactory
 * @see RedisTemplate
 * @see KeyGenerator
 */
@Configuration
@EnableCaching
@ComponentScan("com.kingdowin.xiugr.server")
@PropertySource("classpath:/redis.properties")
public class RedisCacheConfig extends CachingConfigurerSupport {


    private static final ResourceBundle bundle = ResourceBundle.getBundle("redis");

    private String redisHost = bundle.getString("redis.ip");
    private int redisPort = Integer.valueOf(bundle.getString("redis.port"));
    private String redisPassword = bundle.getString("redis.auth");
    private int expireTime = Integer.valueOf(bundle.getString("redis.cache.expireTime"));

    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
        // Defaults
        redisConnectionFactory.setHostName(redisHost);
        redisConnectionFactory.setPort(redisPort);
        redisConnectionFactory.setPassword(redisPassword);
        return redisConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(cf);
        return redisTemplate;
    }

    /**
     * 缓存管理器
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        // Number of seconds before expiration. Defaults to unlimited (0)
        cacheManager.setDefaultExpiration(expireTime);// Sets the default expire time (in seconds)
        return cacheManager;
    }

    /**
     * @description 自定义的缓存key的生成策略</br>
     *              若想使用这个key</br>
     *              只需要讲注解上keyGenerator的值设置为customKeyGenerator即可</br>
     * @return 自定义策略生成的key
     */
    @Bean
    public KeyGenerator customKeyGenerator() {
        return (o, method, objects) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(o.getClass().getName());
            sb.append(method.getName());
            for (Object obj : objects) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }

}

配置注解

如果你的项目已经开启了注解的支持,并且已经扫描了配置所在的包,可以略过该步骤
否则请在你的spring配置文件中填写该代码,用以支持spring注解的扫描

    <context:component-scan base-package="com.xx.xx.xx" />  

参考的文章

Redis 缓存 + Spring 的集成示例
Spring Cache注解+Redis
joshua white's blog
Diggs Java | Spring Redis Cache Manager Example

相关文章

网友评论

  • 谦小易:怎么结合哨兵模式使用
    JC_ZHE7:我也有这个疑问。楼主怎么结合
    jsondream:@谦小易 和哨兵没关系吧……
  • 程序员kyle:也感谢你的分享 :+1: :smile:
  • 程序员kyle:发现了个问题
    int redisMaxWait = Integer.valueOf(bundle.getString("redis.pool.maxWait"));
    cacheManager.setDefaultExpiration(redisMaxWait);设置的是缓存的默认过期时间,不是连接的最大等待时间
    jsondream:@_痕迹 是的,谢谢指正,没注意这个,很容易误导人~

本文标题:redis缓存和spring cache的集成

本文链接:https://www.haomeiwen.com/subject/hobqlttx.html