Redis Java使⽤
引入依赖
Java 操作redis的客⼾端有很多.其中最知名的是jedis.
创建maven项⽬,把jedis的依赖拷⻉到pom.xml中
<!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>4.3.2</version> </dependency>
配置端⼝转发
Redis 服务器安装在云服务器上,⽽我们编写的代码则是在本地主机.
可以使⽤端⼝转发的⽅式,直接把服务器的redis端⼝映射到本地.
此时,访问本地的8888,就相当于访问对应服务器的6379
可以在cmd里查看是否映射成功:
注意,xshell 和服务器必须处在连接状态,这样的映射才是有效的.
连接RedisServer
- 使⽤JedisPool描述Redis服务器的位置.使⽤url来表⽰.
- 使⽤ getResource 和服务器建⽴连接.
- 连接使⽤完毕需要close关闭.也可以直接使⽤try⾃动关闭.
- 通过ping⽅法可以检测连接是否正确建⽴.
public static void main(String[] args) {// 连接到 Redis 服务器上.JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");try (Jedis jedis = jedisPool.getResource()) {// redis 的各种命令, 就都对应到 jedis 对象的各种方法.String pong = jedis.ping();System.out.println(pong);}
}
看一些基础操作:
public class RedisDemoGeneric {public static void test1(Jedis jedis) {System.out.println("get 和 set 的使用");// 先清空数据库. 要避免上一组测试的残留数据影响到下一组测试的结果.jedis.flushAll();jedis.set("key", "111");jedis.set("key2", "222");SetParams params = new SetParams();params.ex(10);params.nx();jedis.set("key", "333", params);String value = jedis.get("key");System.out.println("value=" + value);}public static void test2(Jedis jedis) {System.out.println("exists 和 del");jedis.flushAll();jedis.set("key", "111");jedis.set("key2", "222");jedis.set("key3", "333");boolean result = jedis.exists("key");System.out.println("result: " + result);long result2 = jedis.del("key");System.out.println("result2: " + result2);result = jedis.exists("key");System.out.println("result: " + result);result2 = jedis.del("key", "key2", "key3");System.out.println("result2: " + result2);}public static void test3(Jedis jedis) {System.out.println("keys");jedis.flushAll();jedis.set("key", "111");jedis.set("key2", "111");jedis.set("key3", "111");jedis.set("key4", "111");// redis 中的 key 不能重复~ 而且也是不在意顺序的.Set<String> keys = jedis.keys("*");System.out.println(keys);}public static void test4(Jedis jedis) {System.out.println("expire 和 ttl");jedis.flushAll();jedis.set("key", "111");jedis.expire("key", 10);try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}long time = jedis.ttl("key");System.out.println("time: " + time);}public static void test5(Jedis jedis) {System.out.println("type");jedis.flushAll();jedis.set("key", "111");String type = jedis.type("key");System.out.println("type: " + type);jedis.lpush("key2", "111", "222", "333");type = jedis.type("key2");System.out.println("type: " + type);jedis.hset("key3", "f1", "111");type = jedis.type("key3");System.out.println("type: " + type);jedis.sadd("key4", "111", "222", "333");type = jedis.type("key4");System.out.println("type: " + type);jedis.zadd("key5", 10, "zhangsan");type = jedis.type("key5");System.out.println("type: " + type);}public static void main(String[] args) {// 连接到 Redis 服务器上.JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");try (Jedis jedis = jedisPool.getResource()) {// redis 的各种命令, 就都对应到 jedis 对象的各种方法.
// String pong = jedis.ping();
// System.out.println(pong);// test1(jedis);// test2(jedis);// test3(jedis);// test4(jedis);test5(jedis);}}
}
Redis Java 集成到SpringBoot
使⽤SpringBoot连接Redis单机
配置redis服务地址
application.yml:
spring:redis:host: 127.0.0.1port: 8888
创建Controller
此处需要使⽤StringRedisTemplate 实例
@RestController
public class MyController {@Autowiredprivate StringRedisTemplate redisTemplate;
}
前面使用jedis,是通过jedis对象里的各种方法来操作redis的
此处Spring则是通过StringRedisTemplate来操作redis
最原始提供的类是RedisTemplate,StringRedisTemplate是它的子类,专门处理文本数据
函数式接口,相当于一个回调函数,就在会调里,写要执行的redis命令
这里的RedisConnection就代表了redis连接,对标Jedis对象
此处RedisTemplate是把这些操作redis的方法,分成了几个类别,做了进一步封装
execute方法,让我们随时能够执行redis原生命令
// 后续 redis 测试的各种方法, 都通过这个 Controller 提供的 http 接口来触发.
@RestController
public class MyController {@Autowiredprivate StringRedisTemplate redisTemplate;@GetMapping("/testString")@ResponseBodypublic String testString() {redisTemplate.execute((RedisConnection connection) -> {// execute 要求回调方法中必须写 return 语句. 返回个东西.// 这个回调返回的对象, 就会作为 execute 本身的返回值.connection.flushAll();return null;});redisTemplate.opsForValue().set("key", "111");redisTemplate.opsForValue().set("key2", "222");redisTemplate.opsForValue().set("key3", "333");String value = redisTemplate.opsForValue().get("key");System.out.println("value: " + value);return "OK";}@GetMapping("/testList")@ResponseBodypublic String testList() {// 先清除之前的数据.redisTemplate.execute((RedisConnection connection) -> {// execute 要求回调方法中必须写 return 语句. 返回个东西.// 这个回调返回的对象, 就会作为 execute 本身的返回值.connection.flushAll();return null;});redisTemplate.opsForList().leftPush("key", "111");redisTemplate.opsForList().leftPush("key", "222");redisTemplate.opsForList().leftPush("key", "333");String value = redisTemplate.opsForList().rightPop("key");System.out.println("value: " + value);value = redisTemplate.opsForList().rightPop("key");System.out.println("value: " + value);value = redisTemplate.opsForList().rightPop("key");System.out.println("value: " + value);return "OK";}@GetMapping("/testSet")@ResponseBodypublic String testSet() {redisTemplate.execute((RedisConnection connection) -> {connection.flushAll();return null;});redisTemplate.opsForSet().add("key", "111", "222", "333");Set<String> result = redisTemplate.opsForSet().members("key");System.out.println("result: " + result);Boolean exists = redisTemplate.opsForSet().isMember("key", "111");System.out.println("exists: " + exists);Long count = redisTemplate.opsForSet().size("key");System.out.println("count: " + count);redisTemplate.opsForSet().remove("key", "111", "222");result = redisTemplate.opsForSet().members("key");System.out.println("result: " + result);return "OK";}@GetMapping("/testHash")@ResponseBodypublic String testHash() {redisTemplate.execute((RedisConnection connection) -> {connection.flushAll();return null;});redisTemplate.opsForHash().put("key", "f1", "111");redisTemplate.opsForHash().put("key", "f2", "222");redisTemplate.opsForHash().put("key", "f3", "333");String value = (String) redisTemplate.opsForHash().get("key", "f1");System.out.println("value: " + value);Boolean exists = redisTemplate.opsForHash().hasKey("key", "f1");System.out.println("exists: " + exists);redisTemplate.opsForHash().delete("key", "f1", "f2");Long size = redisTemplate.opsForHash().size("key");System.out.println("size: " + size);return "OK";}@GetMapping("/testZSet")@ResponseBodypublic String testZSet() {redisTemplate.execute((RedisConnection connection) -> {connection.flushAll();return null;});redisTemplate.opsForZSet().add("key", "zhangsan", 10);redisTemplate.opsForZSet().add("key", "lisi", 20);redisTemplate.opsForZSet().add("key", "wangwu", 30);Set<String> members = redisTemplate.opsForZSet().range("key", 0, -1);System.out.println("members: " + members);Set<ZSetOperations.TypedTuple<String>> membersWithScore = redisTemplate.opsForZSet().rangeWithScores("key", 0, -1);System.out.println("membersWithScore: " + membersWithScore);Double score = redisTemplate.opsForZSet().score("key", "zhangsan");System.out.println("score: " + score);redisTemplate.opsForZSet().remove("key", "zhangsan");Long size = redisTemplate.opsForZSet().size("key");System.out.println("size: " + size);Long rank = redisTemplate.opsForZSet().rank("key", "lisi");System.out.println("rank: " + rank);return "OK";}
}