⛰️个人主页: 蒾酒
🔥系列专栏:《spring boot实战》
🌊山高路远,行路漫漫,终有归途。
目录
前置条件
已经初始化好一个spring boot项目且版本为3X,项目可正常启动。
初始化教程:
新版idea(2023)创建spring boot3项目-CSDN博客https://blog.csdn.net/qq_62262918/article/details/135785412?spm=1001.2014.3001.5501
1.导依赖
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
如果还没安装redis可以参照这篇:
阿里云ECS使用docke搭建redis服务-CSDN博客https://blog.csdn.net/qq_62262918/article/details/135707725?spm=1001.2014.3001.5502
2.配置连接信息以及连接池参数
application.yml:
server:
port: 8080
spring:
data:
redis: # Redis连接配置
host: localhost # Redis主机地址
port: 6379 # Redis端口号
password: 123456 # 访问Redis所需密码
database: 0 # 使用的数据库编号
lettuce: #Lettuce客户端配置
pool: # 连接池配置
max-active: 8 # 最大活跃连接数
max-wait: -1 # 最大等待时间(-1表示无限等待)
max-idle: 8 # 最大空闲连接数
min-idle: 0 # 最小空闲连接数
修改为你的连接信息即可。
这里要说的是:
Lettuce和Jedis两者都是Java连接Redis的客户端
选择使用Lettuce而不是Jedis的原因如下:
3.配置序列化方式
config目录下新建redis配置类
配置类代码如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author mijiupro
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
// 设置key和value的序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer()); // 设置key的序列化器为StringRedisSerializer
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); // 设置value的序列化器为JdkSerializationRedisSerializer
redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // 设置hash key的序列化器为StringRedisSerializer
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer()); // 设置hash value的序列化器为JdkSerializationRedisSerializer
redisTemplate.afterPropertiesSet(); // 初始化RedisTemplate
return redisTemplate; // 返回配置好的RedisTemplate
}
}
4.编写测试
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 java.util.concurrent.TimeUnit;
@SpringBootTest
public class RedisTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
//测试redis
void contextLoads2() {
//添加缓存键值对name:mijiu并设置过期时间为1小时
stringRedisTemplate.opsForValue().set("name","mijiu",10, TimeUnit.SECONDS);
System.out.println(stringRedisTemplate.opsForValue().get("name"));
}
}
运行测试
测试成功,整合完毕!