导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置文件
spring:
redis:
host: localhost
port: 6379
进行操作
首先要确认一下操作的类型。
- 普通的key-value格式
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
}
@Test
void set() {
ValueOperations ops = redisTemplate.opsForValue();
ops.set("age",41);
}
@Test
void get() {
ValueOperations ops = redisTemplate.opsForValue();
Object age = ops.get("age");
System.out.println(age);
}
- 哈希格式
@Test
void hset() {
HashOperations hashOperations = redisTemplate.opsForHash();
hashOperations.put("info","a","aa");
}
@Test
void hget() {
HashOperations hashOperations = redisTemplate.opsForHash();
Object o = hashOperations.get("info", "a");
System.out.println(o);
}
StringRedisTemplate
其实StringRedisTemplate和RedisTemplate是两种性质一样的东西,区别就是前一个指定了泛型是String类型,后一个指定的泛型是Object类型的。
黑框框中写的其实就是Sting类型的,这就是为什么在黑框框传入的东西在RedisTemplate中找不到的原因,可以使用StringRedisTemplate对其进行查找。
@SpringBootTest
public class test {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
void test() {
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
String name = ops.get("name");
System.out.println(name);
}
}
jedis
这个和lettuce分别是两种客户端,是可以随意选择的。
添加坐标
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
软后切换模式
spring:
redis:
host: localhost
port: 6379
client-type: jedis
就可以了