Redis 整合 Jedis SpringBoot

小咪咪 2022-10-11 01:26 266阅读 0赞

1-Redis 整合 Jedis

1.1-Jedis 环境准备

A、Jedis 的 Jar 包:

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

B、连接 Redis 注意:

  • 禁用 CentOS 7 防火墙:执行命令systemctl stop firewalld.servicesystemctl disable firewalld.service
  • redis.conf 中注释bind 127.0.0.1
  • redis.conf 中修改protected-mode no

C、创建 Jedis 工程:
在这里插入图片描述
在这里插入图片描述

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.learn</groupId>
  7. <artifactId>jedis</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <dependencies>
  10. <dependency>
  11. <groupId>redis.clients</groupId>
  12. <artifactId>jedis</artifactId>
  13. <version>3.3.0</version>
  14. </dependency>
  15. </dependencies>
  16. </project>

D、创建包 com.learn.redis.jedis、类 JedisApiTest

  1. package com.learn.redis.jedis;
  2. import redis.clients.jedis.Jedis;
  3. public class JedisApiTest {
  4. public static void main(String[] args) {
  5. Jedis jedis = new Jedis("192.168.31.80", 6379);
  6. String pong = jedis.ping();
  7. System.out.println("连接成功");
  8. jedis.close();
  9. }
  10. }

1.2-Jedis 常用操作

1.2.1-Jedis Api Key

  1. Jedis jedis = new Jedis("192.168.31.80", 6379);
  2. jedis.set("k1", "v1");
  3. jedis.set("k2", "v2");
  4. jedis.set("k3", "v3");
  5. Set<String> keys = jedis.keys("*");
  6. System.out.println(keys.size());
  7. for (String key : keys) {
  8. System.out.println(key);
  9. }
  10. System.out.println(jedis.exists("k1"));
  11. System.out.println(jedis.ttl("k1"));
  12. System.out.println(jedis.get("k1"));
  13. jedis.close();

1.2.2-Jedis Api String

  1. Jedis jedis = new Jedis("192.168.31.80", 6379);
  2. jedis.mset("str1", "v1", "str2", "v2", "str3", "v3");
  3. System.out.println(jedis.mget("str1", "str2", "str3"));
  4. jedis.close();

1.2.3-Jedis Api List

  1. Jedis jedis = new Jedis("192.168.31.80", 6379);
  2. jedis.lpush("mylist", "a", "b", "c");
  3. List<String> list = jedis.lrange("mylist", 0, -1);
  4. for (String element : list) {
  5. System.out.println(element);
  6. }
  7. jedis.close();

1.2.4-Jedis Api Set

  1. Jedis jedis = new Jedis("192.168.31.80", 6379);
  2. jedis.sadd("orders", "order01");
  3. jedis.sadd("orders", "order02");
  4. jedis.sadd("orders", "order03");
  5. jedis.sadd("orders", "order04");
  6. Set<String> smembers = jedis.smembers("orders");
  7. for (String order : smembers) {
  8. System.out.println(order);
  9. }
  10. jedis.srem("orders", "order02");
  11. jedis.close();

1.2.5-Jedis Api Hash

  1. Jedis jedis = new Jedis("192.168.31.80", 6379);
  2. jedis.hset("hash1", "userName", "lisi");
  3. System.out.println(jedis.hget("hash1", "userName"));
  4. Map<String, String> map = new HashMap<String, String>();
  5. map.put("telphone", "13810169999");
  6. map.put("address", "atguigu");
  7. map.put("email", "abc@163.com");
  8. jedis.hmset("hash2", map);
  9. List<String> result = jedis.hmget("hash2", "telphone", "email");
  10. for (String element : result) {
  11. System.out.println(element);
  12. }
  13. jedis.close();

1.2.6-Jedis Api Zset

  1. Jedis jedis = new Jedis("192.168.31.80", 6379);
  2. jedis.zadd("zset01", 100d, "z3");
  3. jedis.zadd("zset01", 90d, "l4");
  4. jedis.zadd("zset01", 80d, "w5");
  5. jedis.zadd("zset01", 70d, "z6");
  6. Set<String> zrange = jedis.zrange("zset01", 0, -1);
  7. for (String e : zrange) {
  8. System.out.println(e);
  9. }
  10. jedis.close();

1.3-Jedis 实例

1.3.1-手机验证码

功能要求:

  • 输入手机号,点击发送后随机生成 6 位数字码,2 分钟有效。
  • 输入验证码,点击验证,返回成功或失败。
  • 每个手机号每天只能输入 3 次。

在这里插入图片描述


2-Redis 整合 SpringBoot

SpringBoot 整合 Redis 非常简单,只需按如下步骤整合即可:

A、创建 SpringBoot 工程
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
B、pom.xml 中引入 Redis 依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.5.2</version>
  9. <relativePath/>
  10. </parent>
  11. <groupId>com.learn.redis</groupId>
  12. <artifactId>springboot</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springboot</name>
  15. <dependencies>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter</artifactId>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-test</artifactId>
  23. <scope>test</scope>
  24. </dependency>
  25. <!-- Redis -->
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-data-redis</artifactId>
  29. </dependency>
  30. <!-- SpringBoot 2.X 集成 Redis -->
  31. <dependency>
  32. <groupId>org.apache.commons</groupId>
  33. <artifactId>commons-pool2</artifactId>
  34. <version>2.6.0</version>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-web</artifactId>
  39. </dependency>
  40. <dependency>
  41. <groupId>com.fasterxml.jackson.core</groupId>
  42. <artifactId>jackson-core</artifactId>
  43. <version>2.12.1</version>
  44. </dependency>
  45. <dependency>
  46. <groupId>com.fasterxml.jackson.core</groupId>
  47. <artifactId>jackson-annotations</artifactId>
  48. <version>2.11.4</version>
  49. </dependency>
  50. <dependency>
  51. <groupId>com.fasterxml.jackson.core</groupId>
  52. <artifactId>jackson-databind</artifactId>
  53. <version>2.11.4</version>
  54. </dependency>
  55. </dependencies>
  56. <build>
  57. <plugins>
  58. <plugin>
  59. <groupId>org.springframework.boot</groupId>
  60. <artifactId>spring-boot-maven-plugin</artifactId>
  61. </plugin>
  62. </plugins>
  63. </build>
  64. </project>

C、application.properties 添加 Redis 配置

  1. # Redis 服务器地址
  2. spring.redis.host=192.168.31.80
  3. # Redis 服务器端口
  4. spring.redis.port=6379
  5. # Redis 数据库索引(默认为 0)
  6. spring.redis.database=0
  7. # 连接超时时间(毫秒)
  8. spring.redis.timeout=1800000
  9. # 连接池最大连接数(使用负值表示没有限制)
  10. spring.redis.lettuce.pool.max-active=20
  11. # 最大阻塞等待时间(负数表示没限制)
  12. spring.redis.lettuce.pool.max-wait=-1
  13. # 连接池中的最大空闲连接
  14. spring.redis.lettuce.pool.max-idle=5
  15. # 连接池中的最小空闲连接
  16. spring.redis.lettuce.pool.min-idle=0

D、创建包 com.learn.redis.springboot.config,类 RedisConfig

  1. package com.learn.redis.springboot.config;
  2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  3. import com.fasterxml.jackson.annotation.PropertyAccessor;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import org.springframework.cache.CacheManager;
  6. import org.springframework.cache.annotation.CachingConfigurerSupport;
  7. import org.springframework.cache.annotation.EnableCaching;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.data.redis.cache.RedisCacheConfiguration;
  11. import org.springframework.data.redis.cache.RedisCacheManager;
  12. import org.springframework.data.redis.connection.RedisConnectionFactory;
  13. import org.springframework.data.redis.core.RedisTemplate;
  14. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  15. import org.springframework.data.redis.serializer.RedisSerializationContext;
  16. import org.springframework.data.redis.serializer.RedisSerializer;
  17. import org.springframework.data.redis.serializer.StringRedisSerializer;
  18. import java.time.Duration;
  19. @EnableCaching
  20. @Configuration
  21. public class RedisConfig extends CachingConfigurerSupport {
  22. @Bean
  23. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  24. RedisTemplate<String, Object> template = new RedisTemplate<>();
  25. RedisSerializer<String> redisSerializer = new StringRedisSerializer();
  26. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  27. ObjectMapper om = new ObjectMapper();
  28. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  29. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  30. jackson2JsonRedisSerializer.setObjectMapper(om);
  31. template.setConnectionFactory(factory);
  32. // Key 序列化方式
  33. template.setKeySerializer(redisSerializer);
  34. // Value 序列化方式
  35. template.setValueSerializer(jackson2JsonRedisSerializer);
  36. // Value HashMap 序列化方式
  37. template.setHashValueSerializer(jackson2JsonRedisSerializer);
  38. return template;
  39. }
  40. @Bean
  41. public CacheManager cacheManager(RedisConnectionFactory factory) {
  42. RedisSerializer<String> redisSerializer = new StringRedisSerializer();
  43. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  44. // 解决查询缓存转换异常的问题
  45. ObjectMapper om = new ObjectMapper();
  46. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  47. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  48. jackson2JsonRedisSerializer.setObjectMapper(om);
  49. // 配置序列化(解决乱码的问题),过期时间 600 秒
  50. RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
  51. .entryTtl(Duration.ofSeconds(600))
  52. .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
  53. .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
  54. .disableCachingNullValues();
  55. RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
  56. .cacheDefaults(config)
  57. .build();
  58. return cacheManager;
  59. }
  60. }

E、创建包 com.learn.redis.springboot.controller,类 RedisTestController

  1. package com.learn.redis.springboot.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. @RestController
  8. @RequestMapping("/redis/test")
  9. public class RedisTestController {
  10. @Autowired
  11. private RedisTemplate redisTemplate;
  12. @GetMapping
  13. public String testRedis() {
  14. // Redis 设置值
  15. redisTemplate.opsForValue().set("name", "lucy");
  16. // Redis 获取值
  17. String name = (String) redisTemplate.opsForValue().get("name");
  18. return name;
  19. }
  20. }

F、测试

  • 启动项目,访问地址:http://localhost:8080/redis/test

发表评论

表情:
评论列表 (有 0 条评论,266人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot整合Jedis

    文章目录 Jedis操作String类型 Jedis操作Hash类型 我们在使用springboot搭建微服务的时候,在很多时候还是需要redis的高