SpringBoot学习:整合Redis

Posted BESTSK

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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


以上是关于SpringBoot学习:整合Redis的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot学习—— springboot快速整合Redis

springboot整合redis

springboot整合redis

Spring Boot 学习----SpringBoot整合Redis

SpringBoot学习:整合Redis

SpringBoot学习:整合Redis