Spring boot 2.x使用Redis作为缓存应用

因为项目需要,完成redis作为Spring boot 2.x的换存应用  如下是个人在使用的过程中总结到的内容,有需要的同学可以参考

首先安装redis

其次增加maven依赖:



    org.springframework.boot
    spring-boot-starter-cache



    org.springframework.boot
    spring-boot-starter-data-redis


    com.alibaba
    fastjson
    x.x.x


    org.apache.commons
    commons-pool2
    x.x.x
  
application-dev.properties配置:  
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=-1
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)//不要设置成0  
spring.redis.timeout=1000

添加RedisConfig配置

import com.gsww.dgms.util.support.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;


/**
 * RedisConfig class
 *
 * @author caoyhao
 * @date 2019/4/16
 */
@EnableCaching
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * redisTemplate
     *
     * @author caoyhao
     * @date 2019/4/16
     */
    @Bean(name = "redisTemplate")
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        // value值的序列化
        template.setValueSerializer(new RedisSerializer);
        template.setHashValueSerializer(new RedisSerializer);
        // key的序列化采用StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    /**
     * 缓存管理器
     *
     * @author caoyhao
     * @date 2019/4/16
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
                .RedisCacheManagerBuilder
                .fromConnectionFactory(redisConnectionFactory);
        // 生成一个默认配置,通过config对象即可对缓存进行自定义配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // 设置缓存的默认过期时间,也是使用Duration设置  //以分钟为单位  30分钟
          config = config.entryTtl(Duration.ofMinutes(30))
                //不缓存空值
                .disableCachingNullValues();
        return builder.build();
    }

}

定义用于测试的实体User类和服务层UserService   注意实体一定要加  implements Serializable    要不然无法序列化  。

import java.io.Serializable;
 
public class User implements Serializable { 
    private String userName;
    private Integer userAge; 
    public User(String userName, Integer userAge) {
        this.username = userName;
        this.age = userAge;
    } 
    //getter和setter省略 
}
@Service
public class UserServiceImpl implements UserService {
    @Override
    @Cacheable(value = "userService", key = "'getUser_'+#userName")
    public User getUser(String userName) {
        System.out.println(userName + "从数据库获取数据!");
        return new User("CAOPD", 10);
    }
}

后续可以别写测试方法或者接口进行测试 可以看到内容已经保存在redis中

    

你可能感兴趣的:(java)