在Spring Boot中使用Redis,就是通过Jedis,Redisson,lettuce或者将三者封装的其他工具类,操作远程Redis服务器数据的增删改查。直接操作Jedis,Redisson和lettuce偏底层,本文使用将三者封装的spring-data-redis。
Step 1 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Step 2 添加properties配置文件
#redis配置
#Redis服务器地址
spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database=0
#连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=50
#连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=3000
#连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=20
#连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=2
#连接超时时间(毫秒)
spring.redis.timeout=5000
Step 3 使用RedisTemplate编写工具类
package com.xcbeyond.springboot.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/**
* redis操作工具类.</br>
* (基于RedisTemplate)
* @author xcbeyond
* 2018年7月19日下午2:56:24
*/
@Component
public class RedisUtils {
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 读取缓存
*
* @param key
* @return
*/
public String get(final String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 写入缓存
*/
public boolean set(final String key, String value) {
boolean result = false;
try {
redisTemplate.opsForValue().set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 更新缓存
*/
public boolean getAndSet(final String key, String value) {
boolean result = false;
try {
redisTemplate.opsForValue().getAndSet(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 删除缓存
*/
public boolean delete(final String key) {
boolean result = false;
try {
redisTemplate.delete(key);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
Step 4 测试:编写一个测试类,运行,观察远程数据变化情况
package com.xcbeyond.springboot.redis;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*
* @author xcbeyond
* 2018年7月19日下午3:08:04
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RedisTest {
@Resource
private RedisUtils redisUtils;
/**
* 插入缓存数据
*/
@Test
public void set() {
redisUtils.set("redis_key", "redis_vale");
}
/**
* 读取缓存数据
*/
@Test
public void get() {
String value = redisUtils.get("redis_key");
System.out.println(value);
}
}