1.Redis命令
1.1 入门案例操作
@Test
public void testHash() throws InterruptedException {
Jedis jedis = new Jedis("192.168.126.129",6379);
jedis.hset("person", "id", "18");
jedis.hset("person", "name", "hash测试");
jedis.hset("person", "age", "2");
Map<String,String> map = jedis.hgetAll("person");
Set<String> set = jedis.hkeys("person"); //获取所有的key
List<String> list = jedis.hvals("person");
}
@Test
public void testList() throws InterruptedException {
Jedis jedis = new Jedis("192.168.126.129",6379);
jedis.lpush("list", "1","2","3","4");
System.out.println(jedis.rpop("list"));
}
@Test
public void testTx(){
Jedis jedis = new Jedis("192.168.126.129",6379);
//1.开启事务
Transaction transaction = jedis.multi();
try {
transaction.set("a", "a");
transaction.set("b", "b");
transaction.set("c", "c");
transaction.exec(); //提交事务
}catch (Exception e){
transaction.discard();
}
}
2 SpringBoot整合Redis
2.1 编辑pro配置文件
由于redis的IP地址和端口都是动态变化的,所以通过配置文件标识数据. 由于redis是公共部分,所以写到common中.
2.2 编辑配置类
package com.jt.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.Jedis;
@Configuration //标识我是配置类
@PropertySource("classpath:/properties/redis.properties")
public class RedisConfig {
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private Integer port;
@Bean
public Jedis jedis(){
return new Jedis(host, port);
}
}
3 对象与JSON串转化
3.1 对象转化JSON入门案例
package com.jt;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.pojo.ItemDesc;
import org.junit.jupiter.api.Test;