springboot基础五:集成redis

前言

在项目里redis做为缓存已是国际惯例了,那springboot项目里如何能与redis集成进行使用呢?照着教程作吧redis

配置

  1. 引入pomspring

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-redis</artifactId>
      <version>1.4.7.RELEASE</version>
</dependency>
  1. 建立RedisUtil类数据库

@Configuration
public class RedisUtil {
   @Bean
   public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
       RedisTemplate<Object, Object> template = new RedisTemplate<>();
       template.setConnectionFactory(connectionFactory);
       //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
       Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
       ObjectMapper mapper = new ObjectMapper();
       mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
       mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
       serializer.setObjectMapper(mapper);
       template.setValueSerializer(serializer);
       //使用StringRedisSerializer来序列化和反序列化redis的key值
       template.setKeySerializer(new StringRedisSerializer());
       template.afterPropertiesSet();
       return template;
   }
}
  1. application.properties加入配置信息缓存

## Redis 配置
## 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=8
## 链接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
## 链接池中的最大空闲链接
spring.redis.pool.max-idle=8
## 链接池中的最小空闲链接
spring.redis.pool.min-idle=0
## 链接超时时间(毫秒)
spring.redis.timeout=0
  1. 使用: 
    在须要的类里注入RedisTemplate便可springboot

@Autowired
   private RedisTemplate redisTemplate;

springboot配置redis真的是简单至极,赶忙本身试试吧!服务器

相关文章
相关标签/搜索