springboot整合redis

发布时间 2023-05-20 17:18:44作者: Kevin_D7

SpringBoot整合Redis

前言

Redis是一款key-value存储结构的内存级NoSQL数据库

  • 支持多种数据存储格式

  • 支持持久化

  • 支持集群

Redis下载(Windows版)

https://github.com/tporadowski/redis/releases

Redis安装与启动(Windows版)

  • Windows解压安装或一键式安装

  • 服务端启动命令 redis-server.exe redis.windows.conf

  • 客户端启动命令 redis-cli.exe

1、导入redis依赖

  <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>

2、修改配置文件连接本地redis

 spring:
  redis:
  host: localhost
  port: 6379
  database: 2

3、功能测试

 @SpringBootTest
 class SpringbootRedisDemoApplicationTests {
 
  @Autowired
  private StringRedisTemplate stringRedisTemplate;
 
  @Test
  void set() {
  ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
  ops.set("age","22");
 
  }
 
  @Test
  void get() {
  ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
  String age = ops.get("age");
  System.out.println(age);
 
  }
 
 }

4、切换redis默认默认客户端为jedis

  1. 导入依赖

 <dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
 </dependency>
  1. 修改配置文件

 spring:
  redis:
  host: localhost
  port: 6379
  database: 2
  client-type: jedis
  jedis:
  pool:
  max-active: 16
 # client-type: lettuce #默认

lettcus与jedis区别

jedis连接Redis服务器是直连模式,当多线程模式下使用jedis会存在线程安全问题,解决方案可以通过配置连接池使每个连接专用,这样整体性能就大受影响。

lettcus基于Netty框架进行与Redis服务器连接,底层设计中采用StatefulRedisConnection。StatefulRedisConnection自身是线程安全的,可以保障并发访问安全问题,所以一个连接可以被多线程复用。当然lettcus也支持多连接实例一起工作。

 

 

点击查看代码
<details>
<summary>点击查看代码</summary>

点击查看代码
<details>
<summary>点击查看代码</summary>

点击查看代码

```
```
``` ```