Spring Boot1.5.17整合Redis

Spring Boot整合Redis教程
本文详细介绍了如何在Spring Boot项目中整合Redis,包括依赖引入、配置参数、创建工具类及使用示例。适用于Spring Boot 1.4版本以后,通过Spring Boot Autoconfiguration自动配置简化Redis集成。

环境
操作系统:Windows 7 旗舰版
JDK:1.8.0_161
Eclipse:Mars.2 Release (4.5.2)
Spring Boot:1.5.17

步骤
1,引入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

springboot1.4版本以前依赖为spring-boot-starter-redis,springboot1.4版本后依赖为spring-boot-starter-data-redis。

2,配置参数
我们利用spring-boot-autoconfiguration.jar包中已有的RedisAutoConfiguration.class类来获取RedisTemplate对象和StringRedisTemplate对象,这样我们只需要在application.properties中增加相应的参数就可以了。至于需要设置哪些参数,我们可以查看RedisProperties.class的源码(文件目录:spring-boot-autoconfigure-1.5.17.RELEASE.jar\org\springframework\boot\autoconfigure\data\redis),针对里面的配置项设置相应的值。示例如下:

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=172.16.0.104
# Redis服务器连接端口
spring.redis.port=6888
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=2000
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=6000
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=300
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=100
# 连接超时时间(毫秒)
spring.redis.timeout=30000

3,增加Redis工具类,方便存取数据

@Component
public class RedisUtils {
	@Autowired
    	StringRedisTemplate stringRedisTemplate;
	
	public boolean set(String key, String value) {
		try {
        	stringRedisTemplate.opsForValue().set(key, value);
        	
        	return true;
		} catch (Exception e) {
			e.printStackTrace();
			
           	return false;
    	}
	}
	
	public boolean set(String key, String value, long time, TimeUnit timeUnit){
		try {
			if(time>0){
            	stringRedisTemplate.opsForValue().set(key, value, time, timeUnit);  
			}else{
                set(key, value);
			}
            
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            
            return false;
        }
    }
	
	public String get(String key){ 
        return key==null?"":stringRedisTemplate.opsForValue().get(key);
    }
}

工具类增加@Component是为了在使用的时候注入,里面的方法都不是静态的,因为StringRedisTemplate是动态注入的,写成静态方法会报错。

4,使用示例
下面是一个简单的使用示例

@RestController
public class LoginController {
	@Autowired
	RedisUtils redisUtils;
	
	@RequestMapping("/login")
   	public String login() {	
		redisUtils.set("name", "shiyong");
		
        	return redisUtils.get("name");
   	 }
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值