springboot集成redis

    spring全家桶之springboot集成redis。

一:首先引入jar包,maven项目添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二:配置数据源

  properties形式: 

#============== redis ===================
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=
spring.redis.database=1
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=500
spring.redis.pool.min-idle=0
spring.redis.timeout=0
 或者yml形式配置:
 
spring:
  redis:
     host: localhost
     port: 6379
     timeout: 6000
     pool:
        max-total: 10000
 
 
三 缓存服务,用redisTemplate来进行访问
 
/**
* @Author: jeyson
* @Time: 2018/6/6 10:45
* @Description:这里只提供了string类型,可以将其他类型加入
*/
@Service
public class RedisService {
 
@Autowired
 RedisTemplate redisTemplate;
 
public void setCache(String key,String value,int exp){
   ValueOperations<String,String> ops=redisTemplate.opsForValue();
   ops.set(key,value,exp, TimeUnit.SECONDS);
}
 
public String getCache(String key){
    ValueOperations<String,String> ops=redisTemplate.opsForValue();
    return ops.get(key);
  }
 
}
 这里只写了string类型的操作。
四:测试一下
@Test
public void testRedis(){
    String key="jeyson:code:1245";
    redisService.setCache(key,"12341",60);
    System.out.println("验证码:"+redisService.getCache(key));
}

 源码地址:

   https://github.com/LiuJishuai/springboot-study

原文地址:https://www.cnblogs.com/jeyson/p/9147083.html