Java中如何操作Redis

x33g5p2x  于2021-11-09 转载在 Java  
字(2.7k)|赞(0)|评价(0)|浏览(458)

1.准备操作

1.1 新建工程

1.2 sca-jedis工程依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>redis.clients</groupId>
  4. <artifactId>jedis</artifactId>
  5. <version>3.5.2</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>junit</groupId>
  9. <artifactId>junit</artifactId>
  10. <version>4.12</version>
  11. <scope>test</scope>
  12. </dependency>
  13. <dependency>
  14. <groupId>com.google.code.gson</groupId>
  15. <artifactId>gson</artifactId>
  16. <version>2.8.6</version>
  17. </dependency>
  18. </dependencies>

1.3 sca-tempalte工程依赖

  1. <dependencyManagement>
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-dependencies</artifactId>
  6. <version>2.3.2.RELEASE</version>
  7. <scope>import</scope>
  8. <type>pom</type>
  9. </dependency>
  10. </dependencies>
  11. </dependencyManagement>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-web</artifactId>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-data-redis</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-test</artifactId>
  24. <scope>test</scope>
  25. </dependency>
  26. </dependencies>

1.4 测试是否可以连接Redis

  1. package com.jt;
  2. import org.junit.Test;
  3. import redis.clients.jedis.Jedis;
  4. public class JedisTests {
  5. @Test
  6. public void testGetConnection(){
  7. //假如不能连通,要注释掉redis.conf中 bind 127.0.0.1,
  8. //并将protected-mode的值修改为no,然后重启redis再试
  9. Jedis jedis=new Jedis("192.168.126.129",6379);
  10. //jedis.auth("123456");//假如在redis.conf中设置了密码
  11. String ping = jedis.ping();
  12. System.out.println(ping);
  13. }
  14. }

测试结果

注意保持一致:

1.5 修改redis.conf文件

  • /usr/local/docker/redis01/conf/目录下

修改配置文件之后需要重启,然后再测试连接

拓展:设定编译版本

2. 基于Jedis实现对redis中字符串的操作

  1. @Test
  2. public void testString01(){
  3. //1.创建连接对象
  4. Jedis jedis=new Jedis(ip,port);
  5. //2.执行redis读写操作
  6. //2.1想redis中存储字符串数据
  7. jedis.set("id", "100");
  8. jedis.expire("id", 2);
  9. jedis.set("token", UUID.randomUUID().toString());
  10. jedis.incr("id");
  11. Map<String,Object> map=new HashMap<>();
  12. map.put("code", "201");
  13. map.put("name", "redis");
  14. Gson gson=new Gson();
  15. String jsonStr = gson.toJson(map);//将map对象转换为json字符串
  16. jedis.set("lession",jsonStr);
  17. //2.2删除数据
  18. jedis.del("id");
  19. //2.3获取数据
  20. String id=jedis.get("id");
  21. jsonStr=jedis.get("lession");
  22. System.out.println(id);
  23. System.out.println(jsonStr);
  24. //3.释放资源
  25. jedis.close();
  26. }

相关文章

最新文章

更多