pom.xml依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
appliaction.yml:
redis:
database: 0
host: localhost
port: XXXX
password:
jedis:
pool:
max-active: 100
max-idle: 3
max-wait: -1
min-idle: 0
timeout: 1000
Redis实现类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* Author: Chenly
* Date: 2021-03-29 16:14
* Description: Redis测试服务类
*/
@Service
public class RedisService {
@Autowired
private RedisTemplate redisTemplate;
/**
* 普通缓存获取
* @param key
* @return
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.HOURS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 判断某个key是否存在
* @param key
* @return
*/
public boolean keyExists(String key) {
return redisTemplate.hasKey(key);
}
}
需要缓存的serviceImpl:
public JSONObject get(Integer id) {
JSONObject jsonObject = new JSONObject();
if(redisService.keyExists("eip-home-content") && redisService.get("eip-home-content") != null){
jsonObject.put("result", redisService.get("eip-home-content"));
jsonObject.put("message", "首页的栏目信息获取成功!");
logger.info("缓存首页的栏目信息获取成功!");
return jsonObject;
}
//获取信息
List<xxx> XXXList=XXXMapper.selectByPrimaryKey(id);
AriticleResponseDto groupingCategory= GroupingUtil.grouping(oldeipCategory).get(0);
if(XXXList.size()<0){
jsonObject.put("code", 400);
jsonObject.put("message", "信息获取失败!");
logger.error("信息获取失败!");
return jsonObject;
}
redisService.set("eip-home-content",groupingCategory,1);
jsonObject.put("result", groupingCategory);
jsonObject.put("message", "信息获取成功!");
logger.info("信息获取成功!");
return jsonObject;
}
Redis
最新推荐文章于 2025-05-01 17:51:39 发布