在java中操作Redis
Redis的Java客户端有很多,官方推荐的有三种:
* Jedis
* Lettuce
* Redisson
Spring对Redis客户端进行了整合,提供了Spring Data Redis,在Spring Boot项目中还提供了对应的Starter,即spring-boot-starter-data-redis
Jedis的maven坐标
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
使用Jedis操作Redis的步骤:
(1)获取连接
(2)执行操作
(3)关闭连接
package com.itheima.test; import org.junit.Test; import redis.clients.jedis.Jedis; import java.util.Set; /** * 使用Jedis操作Redis */ public class JedisTest { @Test public void testRedis(){ //1、获取连接 Jedis jedis = new Jedis("localhost", 6379); //2、执行具体操作 jedis.set("username", "xiaoming"); String username = jedis.get("username"); System.out.println(username); jedis.hset("myhash", "addr", "beijing"); String addr = jedis.hget("myhash", "addr"); System.out.println(addr); Set<String> keys = jedis.keys("*"); System.out.println(keys.toString()); // jedis.del("username"); //3、关闭连接 jedis.close(); } }
Spring Data Redis
在Spring Boot项目中,可以使用Spring Data Redis来简化Redis操作,maven坐标:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Spring Data Redis中提供了一个高度封装的类:Redis Template,针对jedis客户端中大量api进行了封装归类,将同一类型操作封装为operation接口,具体分类如下:
* ValueOperation:简单K-V操作
* SetOperations:set类型数据操作
* ZSetOperations:zset类型数据操作
* HashOperations:针对map类型的数据操作
* ListOperations:针对list类型的数据操作
spring: application: name: springdataredis_demo #Redis相关配置 redis: host: localhost port: 6379 #password: 130740 database: 0 # redis默认提供了16个数据库,默认进入0号数据库执行操作 jedis: #Redis连接池配置 pool: max-active: 8 #最大连接数 max-wait: 1ms # 连接池最大阻塞等待时间 max-idle: 4 # 连接池中最大的空闲连接 min-idle: 0 # 连接池中最小的空闲连接
config
package com.itheima.config; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * Redis配置类 */ @Configuration public class RedisConfig extends CachingConfigurerSupport { @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){ RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); //默认的Key序列化器为:JdkSerializationRedisSerializer redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setConnectionFactory(connectionFactory); return redisTemplate; } }
package com.itheima;
import org.junit.jupiter.api.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)
class SpringdataredisDemoApplicationTests {
//springboot框架自动装配RedisTemplate类
@Autowired
private RedisTemplate redisTemplate;
/**
* 操作string类型数据
*/
@Test
public void testString(){
redisTemplate.opsForValue().set("city123", "shanghai");
String value = (String) redisTemplate.opsForValue().get("city123");
System.out.println(value);
redisTemplate.opsForValue().set("key1", "value1", 10L, TimeUnit.SECONDS);
Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("city1234", "nanjing");
System.out.println(aBoolean);
}
/**
* 操作Hash类型数据
*/
@Test
public void testHash(){
HashOperations hashOperations = redisTemplate.opsForHash();
//存值
hashOperations.put("002", "name", "xiaoming");
hashOperations.put("002", "age", "20");
hashOperations.put("002", "addr", "anhui");
//取值
String age = (String)hashOperations.get("002", "age");
System.out.println(age);
//获得hash结构中的所有字段
Set keys = hashOperations.keys("002");
System.out.println(keys.toString());
//获取hash结构中所有的值
List values = hashOperations.values("002");
System.out.println(values.toString());
}
/**
* 操作list类型数据
*/
@Test
public void testList(){
ListOperations listOperations = redisTemplate.opsForList();
//存值
listOperations.leftPush("mylist", "a");
listOperations.leftPushAll("mylist", "b", "c", "d");
//取值
List<String> mylist = listOperations.range("mylist", 0, -1);
for(String value : mylist){
System.out.println(value);
}
//获得列表长度
Long size = listOperations.size("mylist");
int lsize = size.intValue();
for (int i = 0; i < lsize; i++) {
//出队列
String element = (String)listOperations.rightPop("mylist");
System.out.println(element);
}
}
/**
* 操作set类型数据
*/
@Test
public void testSet(){
SetOperations setOperations = redisTemplate.opsForSet();
//存值
setOperations.add("myset", "a", "b", "c", "a");
//取值
Set<String> myset = setOperations.members("myset");
for (String s : myset) {
System.out.println(s);
}
//删除成员
setOperations.remove("myset", "a", "b");
//取值
myset = setOperations.members("myset");
for (String s : myset) {
System.out.println(s);
}
}
/**
* 操作ZSet类型的数据
*/
@Test
public void testZSet(){
ZSetOperations zSetOperations = redisTemplate.opsForZSet();
//存值
zSetOperations.add("myZset", "a", 10.0);
zSetOperations.add("myZset", "b", 11.0);
zSetOperations.add("myZset", "c", 12.0);
zSetOperations.add("myZset", "a", 13.0);
//取值
Set<String> myZset = zSetOperations.range("myZset", 0, -1);
for (String s : myZset) {
System.out.println(s);
}
//修改分数
zSetOperations.incrementScore("myZset", "b", 20.0);
myZset = zSetOperations.range("myZset", 0, -1);
for (String s : myZset) {
System.out.println(s);
}
//删除成员
zSetOperations.remove("myZset", "a", "b");
myZset = zSetOperations.range("myZset", 0, -1);
for (String s : myZset) {
System.out.println(s);
}
}
/**
* 通用操作,针对不同的数据类型都可以操作
*/
@Test
public void testCommon(){
//获取Redis中所欲的key
Set keys = redisTemplate.keys("*");
for (Object key : keys) {
System.out.println(key);
}
//判断某个key是否存在
Boolean itcast = redisTemplate.hasKey("itcast");
System.out.println(itcast);
//删除指定key
redisTemplate.delete("city123");
//获取指定key对应的value的数据类型
DataType myset = redisTemplate.type("myset");
System.out.println(myset.name());
}
}