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真的是簡單至極,趕忙本身試試吧!服務器

相關文章
相關標籤/搜索