Redis配置、测试及分布式缓存实现
一、引入Redis依赖
引入spring-boot-starter-data-redis依赖,不需要指定version,默认和springboot的version保持一致
<!-- Redis -->
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、配置Redis
spring: # Redis 配置 redis: database: 3 host: 127.0.0.1 port: 6379 timeout: 5000
1、database指定Redis的数据库索引,Redis默认有16个逻辑数据库(从0到15)
2、host Redis 服务器的地址,如果要部署上线需要改成服务器IP
3、port 部署Redis的端口,一般默认是6379,为了安全也可以进行修改
4、不需要指定username,指定的话也不要写成root !!默认的用户的defult
三、测试Redis
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;/*** @author <a href="https://github.com/lieeew">leikooo</a>* @date 2024/12/25* @description*/
@SpringBootTest
public class RedisTemplate {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Testpublic void testRedis() {ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();String key = "testKey";String value = "testValue";// 1、测试新政和更新操作valueOps.set(key, value, 2, TimeUnit.MINUTES);String storeValue = valueOps.get(key);System.out.println(storeValue); //结果:testValueassertEquals(storeValue, value, "存储的值和预期不一致");// 2、测试修改String updateValue = "updateValue";valueOps.set(key, updateValue);storeValue = valueOps.get(key);System.out.println(storeValue);// 结果:updateValueassertEquals(storeValue, "updateValue", "存储的值和预期不一致");// 3、测试查询操作valueOps.get(key);storeValue = valueOps.get(key);System.out.println(storeValue);// 结果:updateValueassertEquals(storeValue, updateValue, "存储的值和预期不一致");// 4、测试删除操作stringRedisTemplate.delete(key);storeValue = valueOps.get(key);System.out.println(storeValue); //结果:nullassertNull(storeValue, "删除后值不为 null ");}
}
四、Redis分布式缓存的简单实现
@Resourceprivate StringRedisTemplate stringRedisTemplate;public List<Object> getRedisCacheList() {// 限制爬虫 --->一次性只能拿多少条数据// 构建缓存 keyString redisKey = "xxxxxxxxx";// 从 Redis 缓存中查询 ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();String cachedValue = valueOps.get(redisKey);if (cachedValue != null) {// 如果缓存命中,返回结果 List<Object> cachedPage = JSONUtil.toBean(cachedValue, Object.class);return cachedPage;}// 查询数据库,封装数据,具体内容根据业务逻辑封装List<Object> pictureVOPage = new ArrayList<>();// 存入 Redis 缓存 String cacheValue = JSONUtil.toJsonStr(pictureVOPage);// 5 - 10 分钟随机过期,防止雪崩 int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300);valueOps.set(redisKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);// 返回结果 return pictureVOPage;}