行业知识
在Java中操作Redis(详细-->从环境配置到代码实现)
2026-12-04 23:06:17
来源:互联网转载
在Java中操作Redis
文章目录
- 在Java中操作Redis
- 1、介绍
- 2、Jedis
- 3、Spring Data Redis
- 3.1、对String的操作
- 3.2、对哈希类型数据的操作
- 3.3、对list的操作
- 3.4、对set类型的操作
- 3.5、对 ZSet类型的数据(有序集合)
- 3.6、通用类型的操作
1、介绍
Redis 的Java客户端很多,官方推荐的有三种:
-
Jedis
-
Lettuce
-
Redisson
Spring对Redis客户端进行了整合,提供了Spring Data Redis,在Spring Boot项目中还提供了对应的Starter,即spring-boot-starter-data-redis
2、Jedis
Jedis的maven坐标:
redis.clients jedis 2.8.0
使用Jedis操作Redis的步骤:
- 获取连接
- 执行操作关闭连接
- 关闭连接
编写一个测试类测试redis:
package com.mannor.jedisdemo;import org.junit.jupiter.api.Test;import org.springframework.boot.test.context.SpringBootTest;import redis.clients.jedis.Jedis;@SpringBootTestclass JedisDemoApplicationTests { @Test void contextLoads() { //1. 获取连接 Jedis jedis = new Jedis("localhost", 6379); //2. 执行操作关闭连接 jedis.set("name", "mannor"); //3. 关闭连接 jedis.close(); }}在此之前,需要将Redis服务启动起来redis-server.exe
程序运行前:
测试项目运行后:
测试其他:
package com.mannor.jedisdemo;import org.junit.jupiter.api.Test;import org.springframework.boot.test.context.SpringBootTest;import redis.clients.jedis.Jedis;import java.util.Set;@SpringBootTestclass JedisDemoApplicationTests { /** * 使用jedis操作Redis */ @Test void contextLoads() { //1. 获取连接 Jedis jedis = new Jedis("localhost", 6379); //2. 执行操作关闭连接 jedis.set("name", "mannor");//设置 String name = jedis.get("name");//获取 System.out.println(name); jedis.del("name");//删除 jedis.hset("myhash","addr","beijing");//设置哈希表值 String hget = jedis.hget("myhash", "addr");//获取哈希表 System.out.println(hget); Set keys = jedis.keys("*");//获取所有Redis的数据 for(String key:keys){ System.out.println(key); } //3. 关闭连接 jedis.close(); }}测试项目源码:上述测试项目的源码
3、Spring Data Redis
在Spring Boot项目中,可以使用Spring Data Redis来简化Redis操作,maven坐标:
org.springframework.boot spring-boot-starter-data-redis
Spring Data Redis中提供了一个高度封装的类: RedisTemplate,针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口,具体分类如下:
- ValueOperations:简单K-V操作
- SetOperations:set类型数据操作
- ZSetOperations:zset类型数据操作
- HashOperations:针对map类型的数据操作
- ListOperations:针对list类型的数据操作
yml配置文件:
spring: application: name: springdataredis_demo #Redis相关配置 redis: host: localhost port: 6379 #password: 123456 database: 0 #操作的是0号数据库(redis存在0-15号数据库(默认),在命令中使用select来切换) jedis: #Redis连接池配置 pool: max-active: 8 #最大连接数 max-wait: 1ms #连接池最大阻塞等待时间 max-idle: 4 #连接池中的最大空闲连接 min-idle: 0 #连接池中的最小空闲连接
在获取到RedisTemplate对象执行下列语句:
redisTemplate.opsForValue().set("city","beijing");输出:
原因:RedisTemplate在操作Redis数据库的时候,将key做了一个序列化,上述结果就是序列化的结果,为了解决这个问题就要配置一个配置类:
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配置类 */@Configurationpublic class RedisConfig extends CachingConfigurerSupport { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate redisTemplate = new RedisTemplate(); //默认的Key序列化器为:JdkSerializationRedisSerializer redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setConnectionFactory(connectionFactory); return redisTemplate; }}对于接下类的在java中对Redis的操作,我们可以参照Redis中的常用命令
3.1、对String的操作
(ValueOperations接口)示例:
@SpringBootTestclass SpringDataRedisApplicationTests { @Autowired private RedisTemplate redisTemplate; /** * 操作String类型的数据 */ @Test void contextLoads() {//redisTemplate.opsForValue().set("mannor" ,"rediaz"); String mannor = (String) redisTemplate.opsForValue().get("mannor"); System.out.println(mannor); redisTemplate.opsForValue().set("k1", "v1", 10L, TimeUnit.SECONDS); Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("mannor1", "mannor"); System.out.println(aBoolean); }}3.2、对哈希类型数据的操作
@SpringBootTestclass SpringDataRedisApplicationTests { @Autowired private RedisTemplate redisTemplate; /** * 操作hash类型的数据 */ @Test public void hashTest() { HashOperations hashOperations = redisTemplate.opsForHash(); //存 hashOperations.put("002", "name", "zhangsan"); hashOperations.put("002", "age", "20"); hashOperations.put("002", "addr", "beijing"); //取 Object age = hashOperations.get("002", "age");// System.out.println((String) age); //获取所有字段 Set keys = hashOperations.keys("002"); for (Object key : keys) {// System.out.println(key); } //获得hash结构中的所有值 List values = hashOperations.values("002"); for (Object value : values) { System.out.println(value); } }}3.3、对list的操作
@Autowired private RedisTemplate redisTemplate; /** * 操作list类型的数据 */ @Test public void listTest() { ListOperations listOperations = redisTemplate.opsForList(); //存 listOperations.leftPush("list", "00"); listOperations.leftPushAll("list", "01", "02", "03"); //取值 List list = listOperations.range("list", 0, -1); for (Object val : list) { System.out.println(val); } System.out.println("------------------------------------------------------------"); //获取长度来遍历 Long size = listOperations.size("list"); for (int i = 0; i3.4、对set类型的操作
@Autowired private RedisTemplate redisTemplate; /** * 操作Set类型的数据 */ @Test public void testSet() { SetOperations setOperations = redisTemplate.opsForSet(); //存值 setOperations.add("myset", "a", "b", "c", "a"); //取值 Set myset = setOperations.members("myset"); for (String o : myset) { System.out.println(o); } //删除成员 setOperations.remove("myset", "a", "b"); //取值 myset = setOperations.members("myset"); for (String o : myset) { System.out.println(o); } }3.5、对 ZSet类型的数据(有序集合)
@Autowired private RedisTemplate redisTemplate;/** * 操作ZSet类型的数据 */@Testpublic 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 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); }}3.6、通用类型的操作
@Autowired private RedisTemplate redisTemplate; /** * 通用操作,针对不同的数据类型都可以操作 */ @Test public void testCommon() { //获取Redis中所有的key Set keys = redisTemplate.keys("*"); for (String key : keys) { System.out.println(key); } //判断某个key是否存在 Boolean itcast = redisTemplate.hasKey("itcast"); System.out.println(itcast); //删除指定key redisTemplate.delete("myZset"); //获取指定key对应的value的数据类型 DataType dataType = redisTemplate.type("myset"); System.out.println(dataType.name()); }测试项目源代码:https://gitee.com/rediaz/note-management/tree/master/Regis/SpringDataRedis
-
上一篇:夏天如何腌制美味尖椒?