简介
Jedis
Jedis 是早期的 Redis 的 Java 实现客户端,提供了比较全面的 Redis 命令的支持,其官方网址是:http://tool.oschina.net/uploads/apidocs/redis/clients/jedis/Jedis.html
优点:支持全面的 Redis 操作特性(可以理解为 API 比较全面)。
缺点:使用阻塞的 I/O,且其方法调用都是同步的,程序流需要等到 sockets 处理完 I/O 才能执行,不支持异步;
Jedis 客户端实例不是线程安全的,所以需要通过创建连接池来使用 Jedis。
lettuce
lettuce 是一种可扩展的线程安全的 Redis 客户端,支持异步模式。如果避免阻塞和事务操作,如 BLPOP 和 MULTI/EXEC,多个线程就可以共享一个连接。lettuce 底层基于 Netty,支持高级的 Redis 特性,比如哨兵,集群,管道,自动重新连接和 Redis 数据模型。lettuce 的官网地址是:https://lettuce.io/
优点:支持同步异步通信模式;
Lettuce 的 API 是线程安全的,如果不是执行阻塞和事务操作,如 BLPOP 和 MULTI/EXEC,多个线程就可以共享一个连接。
RedisTemplate
Spring 对 Redis 操作的一层封装,他的底层是通过 Jedis、Lettuce 实现的。如果我们使用 spring-boot-starter-data-redis 则默认时 Lettuce。
RedisTemplate 集群
把单机的 yml 文件改一下就可以了
spring:data:redis:database: 0# 没有密码#password: 123456cluster:# 获取失败 最大重定向次数max-redirects: 3nodes:- 192.168.64.100:6381- 192.168.64.100:6382- 192.168.64.100:6383- 192.168.64.100:6384- 192.168.64.100:6385lettuce:pool:max-active: 8max-wait: -1msmax-idle: 8min-idle: 0cluster:refresh:#支持集群拓扑动态感应刷新,自适应拓扑刷新是否使用所有可用的更新,默认false关闭adaptive: true#刷新周期period: 2000
RedisTemplate 单机
pom.xml 文件引入依赖
<!--SpringBoot与Redis整合依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency>
yml 配置
spring:data:redis:database: 0host: 192.168.64.100port: 6379# 没有密码#password: 123456lettuce:pool:max-active: 8max-wait: -1msmax-idle: 8min-idle: 0
OrderController
@RestController
public class OrderController {@Autowiredprivate OrderService orderService;@PostMapping("/addOrder")public Long addOrder(){//测试就不传参数了return orderService.addOrder();}@GetMapping("/getOrder")public String getOrder(Long id){return orderService.getOrder(id);}//路径传参请求----> http://localhost:8080/getOrderById/164@GetMapping("/getOrderById/{id}")public String getOrderByid(@PathVariable("id") Integer id){return orderService.getOrder(Long.valueOf(id));}
}
OrderService
public interface OrderService {long addOrder();String getOrder(Long id);
}
OrderServiceImpl
@Service
public class OrderServiceImpl implements OrderService {public static final String ORDER_KEY = "order:";//StringRedisTemplate是RedisTemplate的子类@Autowiredprivate StringRedisTemplate redisTemplate;@Overridepublic long addOrder() {//生成订单idlong keyId = ThreadLocalRandom.current().nextLong(1000)+1;//生成订单号String orderNo = UUID.randomUUID().toString();redisTemplate.opsForValue().set(ORDER_KEY+keyId,"京东订单"+ orderNo);//实际场景下,是需要往数据库存的,这里省略return keyId;}@Overridepublic String getOrder(Long id) {return redisTemplate.opsForValue().get(ORDER_KEY+id);}
}
RedisConfig 指定序列化
如果使用的是 StringRedisTemplate 而不是 RedisTemplate 则不需要配置 RedisConfig
RedisTemplate 默认是 JDK 序列化方式
@Configuration
public class RedisConfig {/*** redis序列化的工具配置类,下面这个请一定开启配置* 127.0.0.1:6379> keys ** 1) "ord:102" 序列化过* 2) "\xac\xed\x00\x05t\x00\aord:102" 野生,没有序列化过* this.redisTemplate.opsForValue(); //提供了操作string类型的所有方法* this.redisTemplate.opsForList(); // 提供了操作list类型的所有方法* this.redisTemplate.opsForSet(); //提供了操作set的所有方法* this.redisTemplate.opsForHash(); //提供了操作hash表的所有方法* this.redisTemplate.opsForZSet(); //提供了操作zset的所有方法* @param lettuceConnectionFactory* @return*/@Beanpublic RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(lettuceConnectionFactory);//设置key序列化方式stringredisTemplate.setKeySerializer(new StringRedisSerializer());//设置value的序列化方式json,使用GenericJackson2JsonRedisSerializer替换默认序列化redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.afterPropertiesSet();return redisTemplate;}
}
视图
Jedis
pom.xml 文件引入 jedis
<!--jedis--><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency>
demo
// 创建jedis对象 这里的IP和端口号一般写在配置文件里Jedis jedis = new Jedis("192.168.64.100",6379);// 认证 jedis的密码 如果有的话//jedis.auth("111111");//客户端完成,可以进行操作System.out.println(jedis.ping());//keySet<String> keys = jedis.keys("*");for (String key : keys) {System.out.println(key);}System.out.println("jedis.exists====>"+jedis.exists("k2"));System.out.println(jedis.ttl("k1"));//String//jedis.append("k1","myreids");System.out.println(jedis.get("k1"));jedis.set("k4","k4_redis");System.out.println("----------------------------------------");jedis.mset("str1","v1","str2","v2","str3","v3");System.out.println(jedis.mget("str1","str2","str3"));//listSystem.out.println("----------------------------------------");//jedis.lpush("mylist","v1","v2","v3","v4","v5");List<String> list = jedis.lrange("mylist",0,-1);for (String element : list) {System.out.println(element);}//setjedis.sadd("orders","jd001");jedis.sadd("orders","jd002");jedis.sadd("orders","jd003");Set<String> set1 = jedis.smembers("orders");for (String string : set1) {System.out.println(string);}jedis.srem("orders","jd002");System.out.println(jedis.smembers("orders").size());//hashjedis.hset("hash1","userName","lisi");System.out.println(jedis.hget("hash1","userName"));Map<String,String> map = new HashMap<String,String>();map.put("telphone","138xxxxxxxx");map.put("address","atguigu");map.put("email","zzyybs@126.com");//课后有问题请给我发邮件jedis.hmset("hash2",map);List<String> result = jedis.hmget("hash2", "telphone","email");for (String element : result) {System.out.println(element);}//zsetjedis.zadd("zset01",60d,"v1");jedis.zadd("zset01",70d,"v2");jedis.zadd("zset01",80d,"v3");jedis.zadd("zset01",90d,"v4");List<String> zset01 = jedis.zrange("zset01", 0, -1);zset01.forEach(System.out::println);
视图
lettuce
pom.xml 引入依赖
<!--lettuce--><dependency><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId><version>6.2.1.RELEASE</version></dependency>
demo
//使用构建器 RedisURI.builderRedisURI uri = RedisURI.Builder.redis("192.168.64.100").withPort(6379)//参数1:用户名,参数2:密码.withAuthentication("default","").build();//创建连接客户端RedisClient client = RedisClient.create(uri);StatefulRedisConnection<String, String> conn = client.connect();//操作命令apiRedisCommands<String,String> commands = conn.sync();//keysList<String> list = commands.keys("*");for(String s : list) {System.out.println("s = " + s);}//Stringcommands.set("k1","1111");String s1 = commands.get("k1");System.out.println("String s ==="+s1);//listcommands.lpush("myList2", "v1","v2","v3");List<String> list2 = commands.lrange("myList2", 0, -1);for(String s : list2) {System.out.println("list ssss==="+s);}//setcommands.sadd("mySet2", "v1","v2","v3");Set<String> set = commands.smembers("mySet2");for(String s : set) {System.out.println("set ssss==="+s);}//hashMap<String,String> map = new HashMap<>();map.put("k1","138xxxxxxxx");map.put("k2","atguigu");map.put("k3","zzyybs@126.com");//课后有问题请给我发邮件commands.hmset("myHash2", map);Map<String,String> retMap = commands.hgetall("myHash2");for(String k : retMap.keySet()) {System.out.println("hash k="+k+" , v=="+retMap.get(k));}//zsetcommands.zadd("myZset2", 100.0,"s1",110.0,"s2",90.0,"s3");List<String> list3 = commands.zrange("myZset2",0,10);for(String s : list3) {System.out.println("zset ssss==="+s);}//sortSortArgs sortArgs = new SortArgs();sortArgs.alpha();sortArgs.desc();List<String> list4 = commands.sort("myList2",sortArgs);for(String s : list4) {System.out.println("sort ssss==="+s);}//关闭conn.close();client.shutdown();