赞
踩
Redis的Java客户端很多,官方推荐的有三种:
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需要指定Redis服务器的IP地址和端口号。以下是连接Redis的示例代码:
Jedis jedis = new Jedis("localhost", 6379);
使用Jedis可以执行Redis支持的各种命令,例如set、get、incr等等。以下是一些示例代码:
- // 设置key-value对
- jedis.set("key", "value");
-
- // 获取key对应的value
- String value = jedis.get("key");
-
- // 对key的值进行自增操作
- jedis.incr("key");
使用完Jedis之后,需要关闭连接。以下是关闭连接的示例代码:
jedis.close();
以上是使用Jedis访问Redis的基本步骤。如果需要更详细的信息,可以参考Jedis官方文档:
https://github.com/redis/jedis
Lettuce是一个高性能的Redis客户端,它提供了异步、同步和响应式的API。下面是一些关于如何在Java中通过Lettuce使用Redis的信息:
在Maven项目中,可以通过添加以下依赖来使用Lettuce:
- <dependency>
- <groupId>io.lettuce</groupId>
- <artifactId>lettuce-core</artifactId>
- <version>5.3.3.RELEASE</version>
- </dependency>
可以使用以下代码创建一个Redis连接:
- RedisClient redisClient = RedisClient.create("redis://localhost");
- StatefulRedisConnection<String, String> connection = redisClient.connect();
这将创建一个与本地Redis服务器的连接。
可以使用以下代码执行Redis操作:
- RedisCommands<String, String> syncCommands = connection.sync();
- syncCommands.set("key", "value");
- String value = syncCommands.get("key");
这将设置一个键值对并获取它的值。
在完成Redis操作后,应该关闭Redis连接:
- connection.close();
- redisClient.shutdown();
这将关闭与Redis服务器的连接并释放资源。
Lettuce官方文档:
https://lettuce.io/core/release/reference/
以下是一些有关如何在Java中通过Lettuce使用Redis的代码:
- import io.lettuce.core.RedisClient;
- import io.lettuce.core.RedisCommands;
- import io.lettuce.core.api.StatefulRedisConnection;
- import io.lettuce.core.api.sync.RedisCommands;
-
- public class LettuceExample {
- public static void main(String[] args) {
- RedisClient redisClient = RedisClient.create("redis://localhost");
- StatefulRedisConnection<String, String> connection = redisClient.connect();
- RedisCommands<String, String> syncCommands = connection.sync();
- syncCommands.set("key", "value");
- String value = syncCommands.get("key");
- System.out.println(value);
- connection.close();
- redisClient.shutdown();
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Redisson是一个基于Redis的Java客户端,它提供了许多方便的功能和API来使用Redis。以下是如何在Java中使用Redisson连接Redis的步骤:
- <dependency>
- <groupId>org.redisson</groupId>
- <artifactId>redisson</artifactId>
- <version>3.15.5</version>
- </dependency>
- Config config = new Config();
- config.useSingleServer().setAddress("redis://localhost:6379");
-
- RedissonClient redisson = Redisson.create(config);
- // 获取字符串
- RBucket<String> bucket = redisson.getBucket("myKey");
- String value = bucket.get();
-
- // 设置字符串
- bucket.set("myValue");
-
- // 获取Map
- RMap<String, String> map = redisson.getMap("myMap");
- String mapValue = map.get("myMapKey");
-
- // 设置Map
- map.put("myMapKey", "myMapValue");
Redisson官方文档:https://redisson.org/
Spring Data Redis中提供了一个高度封装的类:RedisTemplate,针对Jedis客户端中大量API进行了归类封装,将同一类型操作封装为operation接口,具体分类如下:
注意: RedisTemplate在操作Redis时默认对Key进行了序列化,使用的是StringRedisSerializer进行序列化。 这是因为Redis的Key必须是字符串类型,而Java中的对象类型需要进行序列化才能转化为字符串类型。 因此,RedisTemplate使用默认的StringRedisSerializer对Key进行序列化,将Java对象转化为字符串类型作为Redis的Key。 如果需要自定义Key的序列化方式,可以通过RedisTemplate的setKeySerializer方法设置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配置类
- */
-
- @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;
- }
-
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- /*
- * Key-Value类型
- * */
- @Test
- public void testString() {
- //ValueOperations valueOperations = redisTemplate.opsForValue();
- //redisTemplate.opsForValue().set("city123","beijing");
- System.out.println("city123:" + redisTemplate.opsForValue().get("city123"));
- 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", "address", "beijing");
-
- //取值
- String name = (String) hashOperations.get("002", "name");
- String age = (String) hashOperations.get("002", "age");
- System.out.println("name:" + name + " age:" + age);
-
- //获得Hash结构中的所有字段
- 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);
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- /*
- * 操作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);
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- /*
- * 操作Set类型的数据
- * */
- @Test
- public void testSet() {
- SetOperations setOperations = redisTemplate.opsForSet();
-
- //存值
- setOperations.add("mySet", "a", "b", "c", "a");
-
- //取值
- Set<String> mySet = setOperations.members("mySet");
- for (String value : mySet) {
- System.out.println(value);
- }
-
- //删除成员
- setOperations.remove("mySet", "a", "b");
-
- System.out.println("----------------");
- //再次取值
- for (String value : mySet) {
- System.out.println(value);
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- /*
- * 操作ZSet类型数据
- * */
- @Test
- public void testZSet() {
- ZSetOperations zSetOperations = redisTemplate.opsForZSet();
-
- //存值
- zSetOperations.add("myZSet", "a", 10.0);
- zSetOperations.add("myZSet", "b", 9.0);
- zSetOperations.add("myZSet", "c", 11.0);
- zSetOperations.add("myZSet", "d", 8.0);
-
- //取值
- Set<String> myZSet = zSetOperations.range("myZSet", 0, -1);
- for (String s : myZSet) {
- System.out.println(s);
- }
-
- //修改分数
- zSetOperations.incrementScore("myZSet", "b", 20.0);
-
- //删除成员
- zSetOperations.remove("myZSet", "d");
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- /*
- * 通用操作,针对不同的数据类型都可以操作
- * */
- @Test
- public void testCommon() {
- //获取Redis中所有的Key
- Set<String> keys = redisTemplate.keys("*");
- for (String key : keys) {
- System.out.println(key);
- }
-
- //判断某个Key是否存在
- System.out.println("------------------");
- Boolean itcast = redisTemplate.hasKey("itcast");
- System.out.println(itcast);
-
- //删除指定Key
- redisTemplate.delete("city123");
-
- //获取指定Key对应的value的数据类型
- System.out.println("------------------");
- DataType dataType = redisTemplate.type("myZSet");
- System.out.println(dataType.name());
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。