SpringBoot项目整合Redis作为缓存中间件的详细步骤
- 1.链接
- 2.整合步骤
- 3.测试Demo
- 4.遇到的问题
- 5.待考虑问题
有更好的建议,欢迎评论区留言~
有不详细或者不准确的地方,欢迎评论区指正~
有技术群嘛 hahh 可以拉我么 ~
1.链接
哔哩教程视频
Redis官方
2.整合步骤
1.添加pom依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
2.配置yml文件
yml配置,安装redis时设置了密码,就需要配置 password
spring:redis:host: 192.168.13.128port: 6379password: 123456
3.使用springBoot自动配置
(RedisAutoConfiguration) 的 redisTemplate/stringRedisTemplate
3.测试Demo
使用的是自动配置的stringRedisTemplate
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.UUID;@Slf4j
@SpringBootTest
class PuductApplicationTests {@Autowiredprivate StringRedisTemplate stringRedisTemplate;@Testpublic void teststringRedisTemplate(){ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();ops.set("我是key","我是value值"+ UUID.randomUUID().toString());String hello = ops.get("我是key");System.out.println("之前保存的:"+ hello);}
}
业务中存取对象
public Map<String, List<Catalog2Vo>> getCatalogJson() {String catalogJson = redisTemplate.opsForValue().get("catalogJson");if(StringUtil.isEmpty(catalogJson)) {Map<String, List<Catalog2Vo>> catalogJsonDB = getCatalogJsonFromDB(); //查询数据库catalogJson = JSON.toJSONString(catalogJsonDB); //对象转json字符串redisTemplate.opsForValue().set("catalogJson",catalogJson);return catalogJsonDB;}Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJson,new TypeReference<Map<String, List<Catalog2Vo>>>(){});return result;}
4.遇到的问题
压测产生堆外内存溢出 OutOfDirectMemoryError 分析:
1)、SpringBoot2.0
以后默认使用 Lettuce
操作 Redis 的客户端,它使用 Netty
进行网络通信
2)、Lettuce
的 bug 导致 Netty 堆外内存溢出 可设置:-Dio.netty.maxDirectMemory
解决方案:(不能直接使用-Dio.netty.maxDirectMemory去调大堆外内存)
方案 | 内容 |
---|---|
方案一 | 升级 Lettuce 客户端。(优点使用 Netty 作为底层网络框架,吞吐量大) |
方案二 | 切换使用 Jedis (缺点许久未更新) |
如果使用方案二,data-redis 里面排除 lettuce-core
再引入 jedis , springboot 里面有该依赖,所以不用写版本号
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><exclusions><exclusion><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></exclusion></exclusions></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency>
5.待考虑问题
- 分布式项目,线程数据不一致,加锁问题
- 缓存击穿、穿透、雪崩问题的解决