1.创建springboot项目 选择依赖
2.启动redis服务端 没有去官网下一个 ,傻瓜式安装(window版本)
3.在测试类中进行测试
package com.hdjy;
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.ValueOperations;
@SpringBootTest
class NosqlRedisApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void set() {
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("name","sun");
}
@Test
void get() {
ValueOperations valueOperations = redisTemplate.opsForValue();
Object name = valueOperations.get("name");
System.out.println(name);
}
}
执行结果
不过这种方法不能跟控制台的redis同步存取,因为控制台存入是字符串类型,RedisTemplate 是以对象的方式存入。如图
我们可以使用StringRedisTemplate解决
package com.hdjy;
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;
@SpringBootTest
class NosqlRedisApplicationTests2 {
@Autowired
private StringRedisTemplate redisTemplate;
@Test
void set() {
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("name","sun");
}
@Test
void get() {
ValueOperations valueOperations = redisTemplate.opsForValue();
Object name = valueOperations.get("name");
System.out.println(name);
}
}
此时控制台也可以取到
如果想用jedis方式连接redis 1.引入依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.配置文件中配置信息
spring:
redis:
host: localhost
port: 6379
client-type: jedis
当不配置jedis时, client-type默认是lettuce
|