当前位置:   article > 正文

如何在Java中操作Redis_java中redis的使用1

java中redis的使用1

Redis的Java客户端很多,官方推荐的有三种:

  1. Jedis
  2. Lettuce
  3. Redisson

Spring对Redis客户端进行了整合,提供了Spring Data Redis,在Spring Boot项目中还提供了对应的Starter,即spring-boot-starter-data-redis。

目录

目录

1.利用Jedis操作Redis:

1.1 连接Redis

1.2 执行Redis命令

1.3 关闭连接

2.利用Lettuce操作Redis:

2.1 添加Lettuce依赖

2.2 创建Redis连接

2.3 执行Redis操作

2.4 关闭Redis连接

3.利用Redisson操作Redis:

3.1 添加Redisson依赖

3.2 创建Redisson客户端

3.3 使用Redisson客户端操作Redis

Spring Data Redis

序列化器编写如下:

操作Key-Value类型数据:

操作Hash类型数据:

操作List类型数据:

操作Set类型数据:

操作ZSet类型数据:

通用操作:


1.利用Jedis操作Redis:

Jedis的Maven坐标:

  1. <dependency>
  2. <groupId>redis.clients</groupId>
  3. <artifactId>jedis</artifactId>
  4. <version>2.8.0</version>
  5. </dependency>

1.1 连接Redis

使用Jedis连接Redis需要指定Redis服务器的IP地址和端口号。以下是连接Redis的示例代码:

Jedis jedis = new Jedis("localhost", 6379);

1.2 执行Redis命令

使用Jedis可以执行Redis支持的各种命令,例如set、get、incr等等。以下是一些示例代码:

  1. // 设置key-value对
  2. jedis.set("key", "value");
  3. // 获取key对应的value
  4. String value = jedis.get("key");
  5. // 对key的值进行自增操作
  6. jedis.incr("key");

1.3 关闭连接

使用完Jedis之后,需要关闭连接。以下是关闭连接的示例代码:

jedis.close();

以上是使用Jedis访问Redis的基本步骤。如果需要更详细的信息,可以参考Jedis官方文档:

https://github.com/redis/jedis


2.利用Lettuce操作Redis:

Lettuce是一个高性能的Redis客户端,它提供了异步、同步和响应式的API。下面是一些关于如何在Java中通过Lettuce使用Redis的信息:

2.1 添加Lettuce依赖

在Maven项目中,可以通过添加以下依赖来使用Lettuce:

  1. <dependency>
  2. <groupId>io.lettuce</groupId>
  3. <artifactId>lettuce-core</artifactId>
  4. <version>5.3.3.RELEASE</version>
  5. </dependency>

2.2 创建Redis连接

可以使用以下代码创建一个Redis连接:

  1. RedisClient redisClient = RedisClient.create("redis://localhost");
  2. StatefulRedisConnection<String, String> connection = redisClient.connect();

这将创建一个与本地Redis服务器的连接。

2.3 执行Redis操作

可以使用以下代码执行Redis操作:

  1. RedisCommands<String, String> syncCommands = connection.sync();
  2. syncCommands.set("key", "value");
  3. String value = syncCommands.get("key");

这将设置一个键值对并获取它的值。

2.4 关闭Redis连接

在完成Redis操作后,应该关闭Redis连接:

  1. connection.close();
  2. redisClient.shutdown();

这将关闭与Redis服务器的连接并释放资源。

Lettuce官方文档:

https://lettuce.io/core/release/reference/

以下是一些有关如何在Java中通过Lettuce使用Redis的代码:

  1. import io.lettuce.core.RedisClient;
  2. import io.lettuce.core.RedisCommands;
  3. import io.lettuce.core.api.StatefulRedisConnection;
  4. import io.lettuce.core.api.sync.RedisCommands;
  5. public class LettuceExample {
  6. public static void main(String[] args) {
  7. RedisClient redisClient = RedisClient.create("redis://localhost");
  8. StatefulRedisConnection<String, String> connection = redisClient.connect();
  9. RedisCommands<String, String> syncCommands = connection.sync();
  10. syncCommands.set("key", "value");
  11. String value = syncCommands.get("key");
  12. System.out.println(value);
  13. connection.close();
  14. redisClient.shutdown();
  15. }
  16. }


3.利用Redisson操作Redis:

Redisson是一个基于Redis的Java客户端,它提供了许多方便的功能和API来使用Redis。以下是如何在Java中使用Redisson连接Redis的步骤:

3.1 添加Redisson依赖

  1. <dependency>
  2. <groupId>org.redisson</groupId>
  3. <artifactId>redisson</artifactId>
  4. <version>3.15.5</version>
  5. </dependency>

3.2 创建Redisson客户端

  1. Config config = new Config();
  2. config.useSingleServer().setAddress("redis://localhost:6379");
  3. RedissonClient redisson = Redisson.create(config);

3.3 使用Redisson客户端操作Redis

  1. // 获取字符串
  2. RBucket<String> bucket = redisson.getBucket("myKey");
  3. String value = bucket.get();
  4. // 设置字符串
  5. bucket.set("myValue");
  6. // 获取Map
  7. RMap<String, String> map = redisson.getMap("myMap");
  8. String mapValue = map.get("myMapKey");
  9. // 设置Map
  10. map.put("myMapKey", "myMapValue");

Redisson官方文档:https://redisson.org/


Spring Data Redis

Spring Data Redis中提供了一个高度封装的类:RedisTemplate,针对Jedis客户端中大量API进行了归类封装,将同一类型操作封装为operation接口,具体分类如下:

  • ValueOperations:简单K-V操作
  • SetOperations:无序集合类型数据操作
  • ZSetOperations:有序集合类型数据操作
  • HashOperations:针对Map类型的数据操作
  • ListOperations:针对List类型的数据操作

注意: RedisTemplate在操作Redis时默认对Key进行了序列化,使用的是StringRedisSerializer进行序列化。 这是因为Redis的Key必须是字符串类型,而Java中的对象类型需要进行序列化才能转化为字符串类型。 因此,RedisTemplate使用默认的StringRedisSerializer对Key进行序列化,将Java对象转化为字符串类型作为Redis的Key。 如果需要自定义Key的序列化方式,可以通过RedisTemplate的setKeySerializer方法设置Key的序列化器。

序列化器编写如下:

  1. package com.itheima.config;
  2. import org.springframework.cache.annotation.CachingConfigurerSupport;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.data.redis.connection.RedisConnectionFactory;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import org.springframework.data.redis.serializer.StringRedisSerializer;
  8. /**
  9. * Redis配置类
  10. */
  11. @Configuration
  12. public class RedisConfig extends CachingConfigurerSupport {
  13. @Bean
  14. public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
  15. RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
  16. //默认的Key序列化器为:JdkSerializationRedisSerializer
  17. redisTemplate.setKeySerializer(new StringRedisSerializer());
  18. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  19. redisTemplate.setConnectionFactory(connectionFactory);
  20. return redisTemplate;
  21. }
  22. }

操作Key-Value类型数据:

  1. /*
  2. * Key-Value类型
  3. * */
  4. @Test
  5. public void testString() {
  6. //ValueOperations valueOperations = redisTemplate.opsForValue();
  7. //redisTemplate.opsForValue().set("city123","beijing");
  8. System.out.println("city123:" + redisTemplate.opsForValue().get("city123"));
  9. redisTemplate.opsForValue().set("key1", "value1", 10L, TimeUnit.SECONDS);
  10. Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("city1234", "nanjing");
  11. System.out.println(aBoolean);
  12. }

操作Hash类型数据:

  1. //操作Hash类型数据
  2. @Test
  3. public void testHash() {
  4. HashOperations hashOperations = redisTemplate.opsForHash();
  5. //存值
  6. hashOperations.put("002", "name", "xiaoming");
  7. hashOperations.put("002", "age", "20");
  8. hashOperations.put("002", "address", "beijing");
  9. //取值
  10. String name = (String) hashOperations.get("002", "name");
  11. String age = (String) hashOperations.get("002", "age");
  12. System.out.println("name:" + name + " age:" + age);
  13. //获得Hash结构中的所有字段
  14. Set keys = hashOperations.keys("002");
  15. for (Object key : keys) {
  16. System.out.println(key);
  17. }
  18. //获得Hash结构中的所有值
  19. List values = hashOperations.values("002");
  20. for (Object value : values) {
  21. System.out.println(value);
  22. }
  23. }

操作List类型数据:

  1. /*
  2. * 操作List类型数据
  3. * */
  4. @Test
  5. public void testList() {
  6. ListOperations listOperations = redisTemplate.opsForList();
  7. //存值
  8. listOperations.leftPush("myList", "a");
  9. listOperations.leftPushAll("myList", "b", "c", "d");
  10. //取值
  11. List<String> myList = listOperations.range("myList", 0, -1);
  12. for (String value : myList) {
  13. System.out.println(value);
  14. }
  15. //获得列表长度
  16. Long size = listOperations.size("myList");
  17. int lSize = size.intValue();
  18. for (int i = 0; i < lSize; i++) {
  19. //出队列
  20. String element = (String) listOperations.rightPop("myList");
  21. System.out.println(element);
  22. }
  23. }

操作Set类型数据:

  1. /*
  2. * 操作Set类型的数据
  3. * */
  4. @Test
  5. public void testSet() {
  6. SetOperations setOperations = redisTemplate.opsForSet();
  7. //存值
  8. setOperations.add("mySet", "a", "b", "c", "a");
  9. //取值
  10. Set<String> mySet = setOperations.members("mySet");
  11. for (String value : mySet) {
  12. System.out.println(value);
  13. }
  14. //删除成员
  15. setOperations.remove("mySet", "a", "b");
  16. System.out.println("----------------");
  17. //再次取值
  18. for (String value : mySet) {
  19. System.out.println(value);
  20. }
  21. }

操作ZSet类型数据:

  1. /*
  2. * 操作ZSet类型数据
  3. * */
  4. @Test
  5. public void testZSet() {
  6. ZSetOperations zSetOperations = redisTemplate.opsForZSet();
  7. //存值
  8. zSetOperations.add("myZSet", "a", 10.0);
  9. zSetOperations.add("myZSet", "b", 9.0);
  10. zSetOperations.add("myZSet", "c", 11.0);
  11. zSetOperations.add("myZSet", "d", 8.0);
  12. //取值
  13. Set<String> myZSet = zSetOperations.range("myZSet", 0, -1);
  14. for (String s : myZSet) {
  15. System.out.println(s);
  16. }
  17. //修改分数
  18. zSetOperations.incrementScore("myZSet", "b", 20.0);
  19. //删除成员
  20. zSetOperations.remove("myZSet", "d");
  21. }

通用操作:

  1. /*
  2. * 通用操作,针对不同的数据类型都可以操作
  3. * */
  4. @Test
  5. public void testCommon() {
  6. //获取Redis中所有的Key
  7. Set<String> keys = redisTemplate.keys("*");
  8. for (String key : keys) {
  9. System.out.println(key);
  10. }
  11. //判断某个Key是否存在
  12. System.out.println("------------------");
  13. Boolean itcast = redisTemplate.hasKey("itcast");
  14. System.out.println(itcast);
  15. //删除指定Key
  16. redisTemplate.delete("city123");
  17. //获取指定Key对应的value的数据类型
  18. System.out.println("------------------");
  19. DataType dataType = redisTemplate.type("myZSet");
  20. System.out.println(dataType.name());
  21. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/812649
推荐阅读
相关标签
  

闽ICP备14008679号