• Redis(四)——Jedis操作Redis6、Redis6与SpringBoot整合


    目录

    Jedis常用操作

    创建测试程序​编辑

    测试相关数据类型

    Jedis-API:    Key

    Jedis-API:    String

    Jedis-API:    List

    Jedis-API:    set

    ​​​​​​​Jedis-API:    hash

    Jedis-API:    zset

    Jedis案例——模拟验证码发送

    SpringBoot整合Redis


    Jedis常用操作

    引入依赖:

    1. <dependency>
    2. <groupId>redis.clientsgroupId>
    3. <artifactId>jedisartifactId>
    4. <version>3.2.0version>
    5. dependency>

    创建测试程序

    1. import redis.clients.jedis.Jedis;
    2. public class Demo01 {
    3. public static void main(String[] args) {
    4. //创建redis对象
    5. Jedis jedis = new Jedis("192.168.137.3",6379);
    6. //ping()方法,如果连接成功则会返回一个值,否则报错
    7. String pong = jedis.ping();
    8. System.out.println("连接成功:"+pong);
    9. jedis.close();
    10. }
    11. }

    禁用Linux的防火墙:Linux(CentOS7)里执行命令(关闭防火墙之后,一定要重启)

    systemctl stop/disable firewalld.service  

    redis.conf中注释掉bind 127.0.0.1 ,然 protected-mode no

    如果之前设置过密码的话,要在创建对象后设置auth

    jedis.auth("你的密码");一定要放在,Jedis jedis = new Jedis("");下面

    测试相关数据类型

    ​​​​​​​Jedis-API:    Key

    1. @Test
    2. public void demo1(){
    3. //创建redis对象
    4. Jedis jedis = new Jedis("192.168.137.3",6379);
    5. //添加key
    6. jedis.set("k1", "v1");
    7. jedis.set("k2", "v2");
    8. jedis.set("k3", "v3");
    9. //参数为“*”表示得到所有的key,返回一个Set集合
    10. Set keys = jedis.keys("*");
    11. System.out.println(keys.size());
    12. for (String key : keys) {
    13. System.out.println(key);
    14. }
    15. System.out.println(jedis.exists("k1"));
    16. System.out.println(jedis.ttl("k1"));
    17. System.out.println(jedis.get("k1"));
    18. }

    ​​​​​​​Jedis-API:    String

    1. //设置多个key-value
    2. jedis.mset("str1","v1","str2","v2","str3","v3");
    3. List mget = jedis.mget("str1","str2","str3");
    4. System.out.println(mget);//输出相应的value

    Jedis-API:    List

    1. jedis.lpush("mylist","lucy","mary","jack");
    2. List list = jedis.lrange("mylist",0,-1);//把所有值都取出来
    3. for (String element : list) {
    4. System.out.println(element);
    5. }

    Jedis-API:    set

    1. //注意key的名字不要和之前冲突
    2. jedis.sadd("orders", "order01");
    3. jedis.sadd("orders", "order02");
    4. jedis.sadd("orders", "order03");
    5. jedis.sadd("orders", "order04");
    6. Set smembers = jedis.smembers("orders");
    7. for (String order : smembers) {
    8. System.out.println(order);
    9. }
    10. jedis.srem("orders", "order02");

    ​​​​​​​Jedis-API:    hash

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

    Jedis-API:    zset

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

    Jedis案例——模拟验证码发送

    要求:

    1、输入手机号,点击发送后随机生成6位数字码,2分钟有效

    随机生成6位数字码:Random

    2分钟有效:把验证码放到redis里面,设置过期时间120秒

    2、输入验证码,点击验证,返回成功或失败

    验证:从redis获取验证码和输入的验证码进行比较

    3、每个手机号每天只能输入3次

    incr(每次发送之后+1)大于2时候,提交不能发送

    1. package com.zqf.jedis_redsidemo;
    2. import redis.clients.jedis.Jedis;
    3. import java.util.Random;
    4. public class PhoneCode {
    5. public static void main(String[] args) {
    6. //模拟验证码
    7. verifyCode("12345678974");
    8. // getRedisCode("12345678974","983534");
    9. }
    10. //1.生成6位数验证码
    11. public static String getCode(){
    12. Random random = new Random();
    13. String code = "";
    14. for (int i=0;i<6;i++){
    15. int i1 = random.nextInt(10);
    16. code += i1;
    17. }
    18. return code;
    19. }
    20. //2.每个手机每天只能发送三次,验证码放到redis中,设置过期时间
    21. public static void verifyCode(String phone){
    22. //连接redis
    23. Jedis jedis = new Jedis("192.168.2.129",6379);
    24. //拼接key
    25. //手机发送次数key
    26. String countKey = "VerifyCode"+phone+":count";
    27. //验证码key
    28. String codeKey = "VerifyCode"+phone+":code" ;
    29. //每个手机每天只能发送三次
    30. String count = jedis.get(countKey); //从redis中取出发送次数
    31. if (count == null){
    32. //没有发送次数 第一次发送
    33. //设置发送次数是1
    34. jedis.setex(countKey,24*60*60,"1"); //key,过期时间,value
    35. }else if (Integer.parseInt(count)<=2){
    36. //发送次数+1
    37. jedis.incr(countKey);
    38. }else if(Integer.parseInt(count)>2){
    39. System.out.println("24h内发送次数已经超过三次");
    40. jedis.close();
    41. return; //三次之后return 以下代码将不执行
    42. }
    43. //发送验证码到redis
    44. String vcode = getCode();
    45. jedis.setex(codeKey,120,vcode);
    46. jedis.close();
    47. }
    48. //3.验证码校验
    49. public static void getRedisCode(String phone,String code){
    50. //从redis里获取验证码
    51. Jedis jedis = new Jedis("192.168.2.129",6379);
    52. //验证码key
    53. String codeKey = "VerifyCode"+phone+":code" ;
    54. String redisCode = jedis.get(codeKey);
    55. //判断
    56. if (code.equals(redisCode)){
    57. System.out.println("成功");
    58. }else {
    59. System.out.println("失败");
    60. }
    61. }
    62. }

    SpringBoot整合Redis

    • 1.引入redis相关依赖
    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-data-redisartifactId>
    4. dependency>
    5. <dependency>
    6. <groupId>org.apache.commonsgroupId>
    7. <artifactId>commons-pool2artifactId>
    8. <version>2.6.0version>
    9. dependency>
    • 2.application.properties配置redis配置 
    1. #Redis服务器地址
    2. spring.redis.host=192.168.xxx.xxx
    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
    • 3.创建配置类,配置Redis里的相关内容
    1. package com.zqf.jedis_redsidemo.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 redisTemplate(RedisConnectionFactory factory) {
    24. RedisTemplate template = new RedisTemplate<>();
    25. RedisSerializer redisSerializer = new StringRedisSerializer();
    26. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    27. ObjectMapper om = new ObjectMapper();//Objectmapper是jackson的依赖,目的把对象写成json格式
    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 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. }
    • 4.RedisTestController中添加测试方法
    1. package com.zqf.jedis_redsidemo.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("/redisTest")
    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. }

  • 相关阅读:
    ThinkPHP框架使用工厂模式对接多个物流公司下单接口架构示例(php7.0及以上)
    如何训练聊天机器人面对复杂的语言环境和需求?
    赚麻了!!!
    Perl中的文件系统守卫:实现自定义访问控制
    贪心算法(算法竞赛、蓝桥杯)--均分纸牌
    python中的变量的定义和使用
    玩转ChatGPT:快速制作PPT
    day07-缓存套餐
    jsp+sql毕业生招聘系统免费系统+论文
    专精特新企业认定条件
  • 原文地址:https://blog.csdn.net/m0_52601969/article/details/126249767