介绍
Redis 的 Java 客户端很多,官方推荐的有三种:
Jedis
Lettuce
Redisson
Spring 对 Redis 客户端进行了整合,提供了 Spring Data Redis,在Spring Boot项目中还提供了对应的Starter,即spring-boot-starter-data-redis,现在常用的方法是这种
Jedis
Jedis的maven坐标:
<dependency>
<groupld>redis.clients</groupld>
<artifactld>jedis</artifactld>
<version>4.1.0</version>
</dependency>
使用Jedis操作Redis的步骤:
//1.获取连接
Jedis jedis = new Jedis("localhost",6379);
jedis.auth("hf");
//2.操作
jedis.set("username","lucy");
String value = jedis.get("username");
System.out.println(value);
//3.关闭连接
jedis.close();
redis设置的没有密码jedis.auth()不用写。
Spring Data Redis
在Spring Boot 项目中,可以使用Spring Data Redis来简化Redis操作,
maven坐标:
<dependency>
<groupld>org.springframework.boot</groupld>
<artifactld>spring-boot-starter-data-redis</artifactld>
</dependency>
Spring Data Redis中提供了一个高度封装的类:RedisTemplate,针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口,具体分类如下:
ValueOperations:简单K-V操作
SetOperations:set类型数据操作
ZSetOperations:zset类型数据操作(也就是sorted list类型)
HashOperations:针对map类型的数据操作
ListOperations:针对list类型的数据操作
applicaton.yml里面配置redis:
#redis配置
redis:
host: 127.0.0.1
port: 6379
password: hf
database: 0
jedis:
#连接池配置
pool:
max-active: 8 #最大连接数
max-wait: 1ms #连接池最大阻塞等待时间
max-idle: 8 #连接池中的最大空闲连接
min-idle: 0 #连接池中的最小空闲连接
我们还需要自己编写一个配置类把RedisTemplate修改一下因为RedisTemplate是自动配置的他的序列化会让key值变得和我们输入的不一样如下图中的"\xac..."一样因此我们需要自己修改一下配置
配置类
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();
//默认的key序列器为jdkSerializationRedisSerializer,可能导致key出现乱码,所以自定义key序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
然后我们建一个测试类看一下是否能成功运行
这样就不是乱码了。
我们可以把这五种类型来测试并熟练命令(这些代码是在测试类中进行的)
package com;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.*;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringBootRedisTest {
@Autowired
private RedisTemplate redisTemplate;
/**
* String类型
*/
@Test
public void test(){
redisTemplate.opsForValue().set("city","beijing");
System.out.println(redisTemplate.opsForValue().get("city"));
}
/**
* Hash类型
*/
@Test
public void testHash(){
//存值
HashOperations hashOperations = redisTemplate.opsForHash();
hashOperations.put("002","name","Maria");
//取值
String name =(String) hashOperations.get("002", "name");
System.out.println(name);
//获取hash中所有的字段名
Set keys = hashOperations.keys("002");
for (Object key : keys) {
System.out.println(key);
}
//获取hash中所有的值
List<Object> values = hashOperations.values("002");
for (Object value : values) {
System.out.println(value);
}
}
/**
* List类型
*/
@Test
public void testList(){
ListOperations listOperations = redisTemplate.opsForList();
//存值
Long leftPush = listOperations.leftPush("list11", "xiaomi");
Long leftPushAll = listOperations.leftPushAll("list11", "huawei", "oppo", "vivo", "apple", "meizu", "oneplus", "realme");
//取值
List <String>list = listOperations.range("list11", 0, -1);
for (String s : list) {
System.out.println(s);
}
//获取长度
Long size = listOperations.size("list11");
int lsize= size.intValue();
for (int i = 0; i < lsize; i++) {
System.out.println(listOperations.index("list11",i));
//出对列
String element = (String) listOperations.rightPop("list11");
System.out.println(element);
}
}
/**
* Set类型
*/
@Test
public void testSet(){
SetOperations setOperations = redisTemplate.opsForSet();
//存值
setOperations.add("myset","a","b","c","d","e");
//取值
Set myset = setOperations.members("myset");
for (Object o : myset) {
System.out.println(o);
}
//删除
Long remove = setOperations.remove("myset", "a", "b");
System.out.println(remove);
}
/**
* ZSet类型
*/
@Test
public void testZSet(){
ZSetOperations zSetOperations = redisTemplate.opsForZSet();
//存值
zSetOperations.add("myzset","a",1.0);
zSetOperations.add("myzset","b",2.0);
zSetOperations.add("myzset","c",3.0);
zSetOperations.add("myzset","d",4.0);
zSetOperations.add("myzset","e",5.0);
//取值
Set <String>myzset = zSetOperations.range("myzset", 0, -1);
for (String s : myzset) {
System.out.println(s);
}
//修改scores
zSetOperations.incrementScore("myzset","a",10.0);
//取值
Set <String>myzset1 = zSetOperations.range("myzset", 0, -1);
for (String s : myzset1) {
System.out.println(s);
}
//删除
zSetOperations.remove("myzset","a","b");
//取值
Set <String>myzset2 = zSetOperations.range("myzset", 0, -1);
for (String s : myzset2) {
System.out.println(s);
}
}
/**
* 通用操作
*/
@Test
public void testCommon(){
//获取redis中所有的key
Set<String> keys = redisTemplate.keys("*");
for (String key : keys)
System.out.println(key);
//判断某个key是否存在
Boolean aBoolean = redisTemplate.hasKey("myset");
System.out.println(aBoolean);
//删除某个key
Boolean delete = redisTemplate.delete("myset");
System.out.println(delete);
//设置某个key的过期时间
Boolean expire = redisTemplate.expire("myzset", 10, TimeUnit.SECONDS);
System.out.println(expire);
//获取某个key的过期时间
Long expire1 = redisTemplate.getExpire("myzset");
System.out.println(expire1);
//获取key的类型
DataType dataType = redisTemplate.type("myzset");
System.out.println(dataType);
}
}