1.首先拥有redis安装完成过的环境
win版的ip地址是localhost
liunx版的ip地址用命令ifconfig查看
liunx版 ./redis-server ./redis.conf开启redis后台服务
liunx版 ./redis-cli进入客户端
2.创建boot项目
2.1在start.spring.io服务器下选择nosql项,选择第一个Spring Data Redis,在pom.xml会自动下载依赖spring-boot-starter-data-redis
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.yml配置文件
spring: redis: # 主机 host: 192.168.241.132 # 端口 port: 6379 # 客户端类型,默认lettuce,jedis客户端线程不安全,lettuce线程安全 client-type: lettuce # 客户端连接池最大值,两个都设比较保险 lettuce: pool: max-active: 14 jedis: pool: max-active: 14
3.测试
package com.example;
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.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import javax.annotation.Resource;
@SpringBootTest
class RedisTemplateBootApplicationTests {
@Resource//按名称注入,autowird是按照类型注入
private RedisTemplate redisTemplate;
@Resource
private StringRedisTemplate stringRedisTemplate;
@Test
void contextLoads() {
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("k1","v1");
Object k1 = valueOperations.get("k1");
System.out.println(k1);
}
@Test
void test(){
ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
stringStringValueOperations.set("age","12");
String age = stringStringValueOperations.get("age");
System.out.println(age);
}
}
4.注意事项
使用RedisTemplate可能会出现序列化问题,idea中的设的键和liunx系统中的key名称不一致现象,出现bug,因此在开发过程中应该首选StringRedisTemplate