Redis-jedis客户端操作
作者:互联网
首先创建一个maven的项目 导入jedis的坐标
<dependencies>
<!-- jedis 坐标-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.1.1</version>
</dependency>
<!-- 测试-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
编写测试类
public class Test {
private Jedis jedis;
@BeforeEach//初始化操作
void setUp() {
//建立连接
jedis=new Jedis("120.77.79.169",6379);
//设置密码
jedis.auth("123321");
//选择库
jedis.select(0);
}
@org.junit.jupiter.api.Test
void name() {
String l = jedis.set("name", "路韶聪");
System.out.println("l = " + l);
String s = jedis.get("name");
System.out.println("s = " + s);
}
@org.junit.jupiter.api.Test
void hashset() {
jedis.hset("name:1","name","路韶聪");
jedis.hset("name:1","age","18");
Map<String, String> stringStringMap = jedis.hgetAll("name:1");
System.out.println("stringStringMap = " + stringStringMap);
}
@AfterEach
void tearDown() {
if (jedis!=null){
jedis.close();
}
}
}
@Autowired//以下是客户端 的操作方法 用stringRedisTemplate 以后用户多的也是这种方法
private StringRedisTemplate stringRedisTemplate;
//json工具 把对象转换为json格式
private static final ObjectMapper objectMapper = new ObjectMapper();
@Test
void te() {
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
ops.set("mgs", "路韶");
}
@Test
void t() {
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
String mgs = ops.get("mgs");
System.out.println("mgs = " + mgs);
}
@Test//存一个user对象
void setUser() throws JsonProcessingException {
User user = new User("周冬雨", 18);
String json = objectMapper.writeValueAsString(user);
stringRedisTemplate.opsForValue().set("user:200",json);//存入对象
String userjson = stringRedisTemplate.opsForValue().get("user:200");
//取出对象
User user1 = objectMapper.readValue(userjson, User.class);
System.out.println("user1 = " + user1);
}
}
<dependencies>
<!-- redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 连接池的依赖commons-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>//json转换工具
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
工具查看存入的数据对象
标签:name,void,Redis,jedis,Test,org,stringRedisTemplate,客户端 来源: https://blog.csdn.net/m0_46570170/article/details/123586441