SpringBoot通过Jedis整合Redis
1.pom.xml添加Jedis依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.application.properties添加Redis配置
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码
spring.redis.password=123456
# 连接超时时间(毫秒)
spring.redis.timeout=10000
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=1000
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=500
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=10000
3.注入JedisPool实例
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class RedisPoolFactory {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.pool.max-active}")
private int maxActive;
@Value("${spring.redis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.pool.min-idle}")
private int minIdle;
@Value("${spring.redis.pool.max-wait}")
private long maxWaitMillis;
//JedisPool的实例注入到spring容器里面
@Bean
public JedisPool JedisPoolFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxWaitMillis(maxWaitMillis);
JedisPool jedisPool = new JedisPool(poolConfig,host,port,timeout,password);
return jedisPool;
}
}
4.创建Redis业务操作类
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@Service
public class RedisService {
@Autowired
private JedisPool jedisPool;
/**
* 获取对象
*/
public <T> T get(String key,Class<T> clazz){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String str = jedis.get(key);
//将String转换为Bean
T t = stringToBean(str,clazz);
return t;
}finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* 设置对象
*/
public <T> boolean set(String key,T value){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//将Bean转换为String
String str = beanToString(value);
if(str == null || str.length() <= 0) {
return false;
}
jedis.set(key, str);
return true;
}finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* 设置对象,含过期时间(单位:秒)
*/
public <T> boolean set(String key,T value,int expireTime){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//将Bean转换为String
String str = beanToString(value);
if(str == null || str.length() <= 0) {
return false;
}
if(expireTime <= 0) {
//有效期:代表不过期
jedis.set(key, str);
}else {
jedis.setex(key, expireTime, str);
}
return true;
}finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* 减少值
*/
public <T> Long decr(String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//返回value减1后的值
return jedis.decr(key);
}finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* 增加值
*/
public <T> Long incr(String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//返回value加1后的值
return jedis.incr(key);
}finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* 删除对象
*/
public boolean delete(String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
long ret = jedis.del(key);
return ret > 0;//删除成功,返回大于0
}finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* 检查key是否存在
*/
public <T> boolean exitsKey(String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.exists(key);
}finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* 将字符串转换为Bean对象
*/
@SuppressWarnings("unchecked")
public static <T> T stringToBean(String str,Class<T> clazz) {
if(str == null || str.length() == 0 || clazz == null) {
return null;
}
if(clazz == int.class || clazz == Integer.class) {
return ((T) Integer.valueOf(str));
}else if(clazz == String.class) {
return (T) str;
}else if(clazz == long.class || clazz == Long.class) {
return (T) Long.valueOf(str);
}else if(clazz == List.class) {
return JSON.toJavaObject(JSONArray.parseArray(str), clazz);
}else {
return JSON.toJavaObject(JSON.parseObject(str), clazz);
}
}
/**
* 将Bean对象转换为字符串类型
*/
public static <T> String beanToString(T value) {
if(value == null){
return null;
}
Class<?> clazz = value.getClass();
if(clazz == int.class || clazz == Integer.class) {
return ""+value;
}else if(clazz == String.class) {
return (String)value;
}else if(clazz == long.class || clazz == Long.class) {
return ""+value;
}else {
return JSON.toJSONString(value);
}
}
}
5.测试缓存
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.com.app.redis.RedisService;
@Controller
public class Test {
@Autowired
private RedisService redisService;
@RequestMapping("/test")
@ResponseBody
public void test() throws Exception {
//普通类型
redisService.set("key1", "hello");
String str = redisService.get("key1",String.class);
System.out.println("读取缓存普通类型:"+str);
//Map集合
Map<String,Object> map = new HashMap<>();
map.put("name", "aaa");
redisService.set("map", map);
Map<String,Object> resultMap = redisService.get("map",Map.class);
System.out.println("读取缓存Map类型:"+resultMap);
//List集合
List<Object> list = new ArrayList<>();
Map<String,Object> map1 = new HashMap<>();
map1.put("name", "bbb");
list.add(map);
list.add(map1);
redisService.set("list", list);
List<Map<String,Object>> resultList = redisService.get("list",List.class);
System.out.println("读取缓存List类型全部元素:"+resultList);
}
}
还没有评论,来说两句吧...