Spring Redis查询缓存

spring boot 版

  • 依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  • yml配置
spring:
  cache:
    type: redis
    cache-names: userCache
  • 添加springboot支持
@EnableCaching
  • 使用
@Cacheable(value = "userCache", key = "#username+'_'+password")
public User findByUsername(String username, String password) {

spring MVC 版

  • 依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
     <version>1.5.10.RELEASE</version>
</dependency>
  • 配置,通过java类配置bean
@Configuration
@EnableCaching
public class CachingConfig {
    /**
     * 连接Redis
     *
     * @return
     */
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        // host地址
        jedisConnectionFactory.setHostName("localhost");
        // 端口号
        jedisConnectionFactory.setPort(6379);
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }
    /**
     * RedisTemplate配置
     * @param redisCF
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory redisCF) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(redisCF);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    /**
     * 缓存管理器
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
        RedisCacheManager cacheManager  =new RedisCacheManager(redisTemplate);
        //设置过期时间
        cacheManager.setDefaultExpiration(3600);
        return cacheManager;
    }
}
  • 使用
@Cacheable(value = "userCache", key = "#username+'_'+password")
public User findByUsername(String username, String password) {

https://zoeminghong.github.io/2016/07/07/redis20160707/

猜你喜欢

转载自blog.csdn.net/lightofsms/article/details/80449800