1. 程式人生 > >SpringBoot學習:整合Redis

SpringBoot學習:整合Redis

專案下載地址:http://download.csdn.NET/detail/aqsunkai/9805821

pom.xml新增對redis的依賴:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-redis -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-redis</artifactId>
      <version>1.4.5.RELEASE</version>
    </dependency>
application.yml配置redis啟動引數:
spring:
    redis:
        # Redis伺服器地址
        host: localhost
        # Redis伺服器連線埠
        port: 6379
        # Redis伺服器連線密碼(預設為空)
        password:
        pool:
           # 連線池最大連線數(使用負值表示沒有限制)
           max-active: 8
           # 連線池中的最大空閒連線
           min-idle: 0
           # 連線池最大阻塞等待時間(使用負值表示沒有限制)
           max-wait: -1
           # 連線池中的最小空閒連線
           max-idle: 8
        # 連線超時時間(毫秒)
        timeout: 20
Redis的啟動類如下:
package com.sun.configuration;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.springframework.boot.bind.RelaxedPropertyResolver;
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.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.lang.reflect.Method;

/**
 * 專案啟動載入redis
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport implements EnvironmentAware {

    private final Logger logger = Logger.getLogger(RedisConfig.class);

    private RelaxedPropertyResolver propertyResolver;

    public void setEnvironment(Environment env) {
        this.propertyResolver = new RelaxedPropertyResolver(env, "spring.redis.");
    }

    @Bean("jedisPool")
    public JedisPool redisPoolFactory() {
        logger.info("redis地址:" + propertyResolver.getProperty("host") +
                ":" + propertyResolver.getProperty("port"));
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(Integer.valueOf(propertyResolver.getProperty("pool.max-idle")));
        jedisPoolConfig.setMaxWaitMillis(Integer.valueOf(propertyResolver.getProperty("pool.max-wait")));

        JedisPool jedisPool = new JedisPool(jedisPoolConfig, propertyResolver.getProperty("host"),
                  Integer.valueOf(propertyResolver.getProperty("port")),
                  Integer.valueOf(propertyResolver.getProperty("timeout")));
        logger.info("jedisPool注入成功!!");
        return jedisPool;
    }
    /**
     * 生成key的策略
     * 快取註解沒有配置key引數走此方法
     * @return
     */
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
    /**
     * RedisTemplate配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
    /**
     * 管理快取
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //設定快取過期時間--一天
        rcm.setDefaultExpiration(86400);//秒
        return rcm;
    }

}
在ServiceImpl業務處理類上使用註解:
@Cacheable(value="common",key="'id_'+#id")
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }
前臺輸入地址呼叫後臺可以看到第一個打印出執行的sql,第二次不列印



專案啟動前需要啟動redis伺服器,不知道的可以參考部落格:http://blog.csdn.net/aqsunkai/article/details/51324176