• redis6.2(二)Redis的新数据类型、使用java语言操作Redis


    redis的安装配置、基本数据类型可以参考: redis6.2(一)安装、配置、常用数据类型

    5、Redis的新数据类型

    (1) Bitmaps

    Redis提供了Bitmaps这个“数据类型”可以实现对位的操作:

    (1) Bitmaps本身不是一种数据类型, 实际上它就是字符串(key-value) , 但是它可以对字符串的位进行操作。

    (2) Bitmaps单独提供了一套命令, 所以在Redis中使用Bitmaps和使用字符串的方法不太相同。 可以把Bitmaps想象成一个以位为单位的数组, 数组的每个单元只能存储0和1, 数组的下标在Bitmaps中叫做偏移量。

    1、setbit

    setbit    <key><offset><value>设置Bitmaps中某个偏移量的值(0或1)
    
    *offset:偏移量从0开始
    
    • 1
    • 2
    • 3

    每个独立用户是否访问过网站存放在Bitmaps中, 将访问的用户记做1, 没有访问的用户记做0, 用偏移量作为用户的id。

    设置键的第offset个位的值(从0算起) , 假设现在有20个用户,userid=1, 6, 11, 15, 19的用户对网站进行了访问, 那么当前Bitmaps初始化结果如图

    在这里插入图片描述

    127.0.0.1:6379> setbit user:20221203 1 1
    (integer) 0
    127.0.0.1:6379> setbit user:20221203 6 1
    (integer) 0
    127.0.0.1:6379> setbit user:20221203 11 1
    (integer) 0
    127.0.0.1:6379> setbit user:20221203 15 1
    (integer) 0
    127.0.0.1:6379> setbit user:20221203 19 1
    (integer) 0
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    注:很多应用的用户id以一个指定数字(例如10000) 开头, 直接将用户id和Bitmaps的偏移量对应势必会造成一定的浪费, 通常的做法是每次做setbit操作时将用户id减去这个指定数字。

    在第一次初始化Bitmaps时, 假如偏移量非常大, 那么整个初始化过程执行会比较慢, 可能会造成Redis的阻塞。

    2、getbit

    getbit  <key><offset>获取Bitmaps中某个偏移量的值
    
    
    # 获取id=8的用户是否在20221203这天访问过, 返回0说明没有访问过:
    127.0.0.1:6379> getbit  user:20221203 8
    (integer) 0
    
    # 获取id=1的用户是否在20221203这天访问过, 返回1说明访问过:
    127.0.0.1:6379> getbit  user:20221203 1
    (integer) 1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    3、bitcount

    统计字符串被设置为1的bit数。一般情况下,给定的整个字符串都会被进行计数,通过指定额外的 start 或 end 参数,可以让计数只在特定的位上进行。start 和 end 参数的设置,都可以使用负数值:比如 -1 表示最后一个位,而 -2 表示倒数第二个位,start、end 是指bit组的字节的下标数,二者皆包含。

    bitcount<key>[start end] 统计字符串从start字节到end字节比特值为1的数量
    
    127.0.0.1:6379> bitcount user:20221203
    (integer) 5
    
    # start和end代表起始和结束字节数, 下面操作计算用户id在第1个字节到第3个字节之间的独立访问用户数, 
    # 对应的用户id是11, 15, 19。
    127.0.0.1:6379> bitcount user:20221203 1 3
    (integer) 3
    
    
    # 举例: k1 【01000001 01000000  00000000 00100001】,对应【0,1,2,3】
    127.0.0.1:6379> setbit k1 1 1
    (integer) 0
    127.0.0.1:6379> setbit k1 7 1
    (integer) 0
    127.0.0.1:6379> setbit k1 9 1
    (integer) 0
    127.0.0.1:6379> setbit k1 26 1
    (integer) 0
    127.0.0.1:6379> setbit k1 31 1
    
    bitcount k1 1 2  : 统计下标1、2字节组中bit=1的个数,即01000000  00000000
    --》bitcount K1 1 2   --》1
    
    bitcount k1 1 3  : 统计下标1、2字节组中bit=1的个数,即01000000  00000000 00100001
    --》bitcount K1 1 3  --》3
    
    bitcount k1 0 -2  : 统计下标0到下标倒数第2,字节组中bit=1的个数,即01000001  01000000   00000000
    --》bitcount K1 0 -2  --》3
    
     # 注意:redis的setbit设置或清除的是bit位置,而bitcount计算的是byte位置。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    4、bitop

    bitop  and(or/not/xor) <destkey> [key…]
    
    # bitop是一个复合操作, 它可以做多个Bitmaps的and(交集) 、 or(并集) 、 not(非) 、 xor(异或) 操作并将结果保存在destkey中。
    
    2022-12-04 日访问网站的userid=1,2,5,9。
    setbit unique:users:20221204 1 1
    setbit unique:users:20221204 2 1
    setbit unique:users:20221204 5 1
    setbit unique:users:20221204 9 1
    
    
    
    2022-12-03 日访问网站的userid=0,1,4,9。
    setbit unique:users:20221203 0 1
    setbit unique:users:20221203 1 1
    setbit unique:users:20221203 4 1
    setbit unique:users:20221203 9 1
    
    # 计算出两天都访问过网站的用户数量
    127.0.0.1:6379> bitop and unique:users:20221203_04 unique:users:20221203 unique:users:20221204
    (integer) 2
    
    # 计算出任意一天都访问过网站的用户数量(例如月活跃就是类似这种) , 可以使用or求并集
    127.0.0.1:6379> bitop or union:users:20221203_04 unique:users:20221203 unique:users:20221204
    (integer) 2
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    Bitmaps与set对比

    假设网站有1亿用户, 每天独立访问的用户有5千万, 如果每天用集合类型和Bitmaps分别存储活跃用户可以得到表

    set和Bitmaps存储一天活跃用户对比
    数据类型每个用户id占用空间需要存储的用户量全部内存量
    集合类型64位5000000064位*50000000 = 400MB
    Bitmaps1位1000000001位*100000000 = 12.5MB

    很明显, 这种情况下使用Bitmaps能节省很多的内存空间, 尤其是随着时间推移节省的内存还是非常可观的

    set和Bitmaps存储独立用户空间对比
    数据类型一天一个月一年
    集合类型400MB12GB144GB
    Bitmaps12.5MB375MB4.5GB

    假如该网站每天的独立访问用户很少, 例如只有10万(大量的僵尸用户) , 那么两者的对比如下表所示, 很显然, 这时候使用Bitmaps就不太合适了, 因为基本上大部分位都是0。

    set和Bitmaps存储一天活跃用户对比(独立用户比较少)
    数据类型每个userid占用空间需要存储的用户量全部内存量
    集合类型64位10000064位*100000 = 800KB
    Bitmaps1位1000000001位*100000000 = 12.5MB

    (2) HyperLogLog

    我们经常会遇到与统计相关的功能需求,比如统计网站PV(PageView页面访问量),可以使用Redis的incr、incrby轻松实现。

    但像UV(UniqueVisitor,独立访客)、独立IP数、搜索记录数等需要去重和计数的问题如何解决?这种求集合中不重复元素个数的问题称为基数问题。

    解决基数问题有很多种方案:

    • (1)数据存储在MySQL表中,使用distinct count计算不重复个数

    • (2)使用Redis提供的hash、set、bitmaps等数据结构来处理

    以上的方案结果精确,但随着数据不断增加,导致占用空间越来越大,对于非常大的数据集是不切实际的。

    能否能够降低一定的精度来平衡存储空间?Redis推出了HyperLogLog

    Redis HyperLogLog 是用来做基数统计的算法,HyperLogLog 的优点是,在输入元素的数量或者体积非常非常大时,计算基数所需的空间总是固定的、并且是很小的。

    在 Redis 里面,每个 HyperLogLog 键只需要花费 12 KB 内存,就可以计算接近 2^64 个不同元素的基数。这和计算基数时,元素越多耗费内存就越多的集合形成鲜明对比。

    但是,因为 HyperLogLog 只会根据输入元素来计算基数,而不会储存输入元素本身,所以 HyperLogLog 不能像集合那样,返回输入的各个元素。

    pfadd

    pfadd     <key>< element> [element ...]   添加指定元素到 HyperLogLog中
    
    # 将所有元素添加到指定HyperLogLog数据结构中。如果执行命令后HLL估计的近似基数发生变化,则返回1,否则返回0。
    127.0.0.1:6379> pfadd k1 v1
    (integer) 1
    127.0.0.1:6379> pfadd k1 v2
    (integer) 1
    127.0.0.1:6379> pfadd k1 v2
    (integer) 0
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    pfcount

    pfcount    <key> [key ...] 计算近似基数,可以计算多个
    
    127.0.0.1:6379> pfcount k1
    (integer) 2
    
    • 1
    • 2
    • 3
    • 4

    pfmerge

    pfmerge   <destkey><sourcekey> [sourcekey ...]  将一个或多个key合并后的结果存储在另一个key中
    
    # 比如每月活跃用户可以使用每天的活跃用户来合并计算可得
    127.0.0.1:6379> pfadd user:20221203 tom
    (integer) 1
    127.0.0.1:6379> pfadd user:20221203 jack
    (integer) 1
    127.0.0.1:6379> pfadd user:20221204 jack
    (integer) 1
    127.0.0.1:6379> pfadd user:20221204 tom
    (integer) 1
    127.0.0.1:6379> pfmerge user:202212 user:20221203 user:20221204
    OK
    127.0.0.1:6379> pfcount user:202212
    (integer) 2
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    (3) Geospatial

    Redis 3.2 中增加了对GEO类型的支持。GEO,Geographic,地理信息的缩写。该类型,就是元素的2维坐标,在地图上就是经纬度。redis基于该类型,提供了经纬度设置,查询,范围查询,距离查询,经纬度Hash等常见操作。

    # 1、geoadd 添加地理位置(经度,纬度,名称)
    geoadd  <key><longitude><latitude><member> [longitude latitude member...]   
    
    
    127.0.0.1:6379> geoadd china:city 121.47 31.23 shanghai
    (integer) 1
    127.0.0.1:6379> geoadd china:city 106.50 29.53 chongqing 114.05 22.52 shenzhen 116.38 39.90 beijing
    (integer) 3
    
    
    # 有效的经度从 -180 度到 180 度。有效的纬度从 -85.05112878 度到 85.05112878 度。
    # 当坐标位置超出指定范围时,该命令将会返回一个错误。
    # 已经添加的数据,是无法再次往里面添加的。
    
    
    # 2、geopos  获得指定地区的坐标值
    geopos  <key><member> [member...]  
    
    127.0.0.1:6379> geopos  china:city shanghai
    1) 1) "121.47000163793563843"
       2) "31.22999903975783553"
       
    # 3、geodist 获取两个位置之间的直线距离
    geodist  <key><member1><member2>  [m|km|ft|mi ]
    
    127.0.0.1:6379> geodist china:city shanghai beijing km
    "1068.1535"
    
    # m 表示单位为米[默认值]。
    # km 表示单位为千米。
    # mi 表示单位为英里。
    # ft 表示单位为英尺。
    # 如果用户没有显式地指定单位参数, 那么 GEODIST 默认使用米作为单位
    
    # 4、georadius 以给定的经纬度为中心,找出某一半径内的元素
    127.0.0.1:6379> georadius china:city 110.00 30.00 1000 km
    1) "chongqing"
    2) "shenzhen"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    6、使用java语言操作Redis(Jedis)

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

    连接Redis注意事项

    禁用Linux的防火墙:Linux(CentOS7)里执行命令
    systemctl stop/disable firewalld.service   
    redis.conf中注释掉bind 127.0.0.1 ,然后设置protected-mode no,最后重新启动服务
    
    • 1
    • 2
    • 3
    package com.yyds.redis;
    
    import redis.clients.jedis.Jedis;
    
    public class HelloJedis {
        public static void main(String[] args) {
    
            // 创建jedis对象
            Jedis jedis = new Jedis("192.168.42.9", 6379);
            
            // 测试是否连接成功
            String res = jedis.ping();
            
            System.out.println(res); // PONG
            
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    (1) Jedis-API: Key

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

    (2) Jedis-API: String

    jedis.mset("str1","v1","str2","v2","str3","v3");
    System.out.println(jedis.mget("str1","str2","str3"));
    
    • 1
    • 2

    (3) Jedis-API: List

    List<String> list = jedis.lrange("mylist",0,-1);
    for (String element : list) {
        System.out.println(element);
    }
    
    • 1
    • 2
    • 3
    • 4

    (4) Jedis-API: set

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

    (5) Jedis-API: hash

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

    (6) Jedis-API: zset

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

    (7) Jedis-案例: 手机验证码功能

    要求:

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

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

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

    package com.yyds.redis;
    
    import redis.clients.jedis.Jedis;
    
    import java.util.Random;
    import java.util.Scanner;
    
    /**
     * 利用redis模拟手机验证码功能
     *
     *
     * 1、输入手机号,点击发送后随机生成6位数字码,2分钟有效
     * 2、输入验证码,点击验证,返回成功或失败
     * 3、每个手机号每天只能输入3次
     */
    public class PhoneCodeTest {
    
        public static Jedis jedis = new Jedis("192.168.42.9", 6379);
    
        public static void main(String[] args) {
            while (true){
                Scanner sc = new Scanner(System.in);
                System.out.println("请输入你的手机号:");
                String phone = sc.nextLine();
                String code = save2Redis(phone);
                if(code == null){
                    break;
                }
                System.out.println("您好" + phone+ ",统一门户动态密码为:" + code +  "。(严禁工号借用,请勿将短信内容告知他人!)【com.yyds】");
                boolean isJump = true;
                for (int i = 0; i < 3; i++) {
                    System.out.println("请输入验证码:");
                    String phoneCode = sc.nextLine();
                    boolean bool = verifyPhoneCode(phone, phoneCode);
                    if(bool){
                        System.out.println("login success......");
                        break;
                    }else {
                        if(i == 2){
                            System.out.println("验证码输入错误3次,请重新获取验证码......");
                            isJump = false;
                        }else {
                            System.out.println("登录失败,请重新输入验证码......");
                        }
                    }
                }
                if (isJump){
                    break;
                }
            }
    
        }
    
        // 模拟收到验证码,进行验证
        public static boolean verifyPhoneCode(String phone, String phoneCode){
            String codeKey = "code_" + phone;
    
            // 从redis中获取该手机号的验证码
            String savePhoneCode = jedis.get(codeKey);
            if(phoneCode.equals(savePhoneCode)){
                return true;
            }
            return false;
        }
        
        // 将手机号保存到redis中,一天只能发送3次
        // 将验证码保存到redis中,有效时间2min
        public static String save2Redis(String phone){
            String phoneKey = "phone_" + phone;
            String codeKey = "code_" + phone;
    
            // 从redis中获取该手机号是否存在
            String count = jedis.get(phoneKey);
            if(count == null){
                // 该手机号第一次发送验证码,设置过期时间24h
                jedis.setex(phoneKey, 24 * 60 * 60, "1");
            }else if(Integer.parseInt(count) <= 2){
                // 该手机号第一次发送验证码
                jedis.incr(phoneKey);
            }else if(Integer.parseInt(count) > 2){
                System.out.println(phone + " 今日已经发送" + count + "次验证码,超出限制,请24h后登录......");
                return null;
            }
            // 模拟生成验证码
            String phoneCode = getPhoneCode();
            // 将验证码保存到redis中,设置过期时间120s
            jedis.setex(codeKey,120,phoneCode);
            return phoneCode;
        }
    
        // 模拟生成手机验证码
        public static String getPhoneCode(){
            Random random = new Random();
            String code = "";
            for (int i = 0; i <= 5; i++) {
                int r = random.nextInt(10);
                code = code + r ;
            }
            return code;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102

    (8)与spring-boot进行整合

    Spring Boot整合Redis非常简单,只需要按如下步骤整合即可

    1、 在pom.xml文件中引入redis依赖
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
        <parent>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-parentartifactId>
            <version>2.2.1.RELEASEversion>
            <relativePath/> 
        parent>
    
        <groupId>com.yydsgroupId>
        <artifactId>sprint_boot_redisartifactId>
        <version>0.0.1-SNAPSHOTversion>
        <name>sprint_boot_redisname>
        <description>Demo project for Spring Bootdescription>
    
    
        <properties>
            <java.version>1.8java.version>
        properties>
    
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
    
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
    
    
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-redisartifactId>
            dependency>
    
            
            <dependency>
                <groupId>org.apache.commonsgroupId>
                <artifactId>commons-pool2artifactId>
                <version>2.6.0version>
            dependency>
    
        dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                plugin>
            plugins>
        build>
        <repositories>
            <repository>
                <id>spring-milestonesid>
                <name>Spring Milestonesname>
                <url>https://repo.spring.io/milestoneurl>
                <snapshots>
                    <enabled>falseenabled>
                snapshots>
            repository>
            <repository>
                <id>spring-snapshotsid>
                <name>Spring Snapshotsname>
                <url>https://repo.spring.io/snapshoturl>
                <releases>
                    <enabled>falseenabled>
                releases>
            repository>
        repositories>
        <pluginRepositories>
            <pluginRepository>
                <id>spring-milestonesid>
                <name>Spring Milestonesname>
                <url>https://repo.spring.io/milestoneurl>
                <snapshots>
                    <enabled>falseenabled>
                snapshots>
            pluginRepository>
            <pluginRepository>
                <id>spring-snapshotsid>
                <name>Spring Snapshotsname>
                <url>https://repo.spring.io/snapshoturl>
                <releases>
                    <enabled>falseenabled>
                releases>
            pluginRepository>
        pluginRepositories>
    
    project>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    2、 application.properties配置redis配置
    #Redis服务器地址
    spring.redis.host=192.168.42.9
    #Redis服务器连接端口
    spring.redis.port=6379
    #Redis数据库索引(默认为0)
    spring.redis.database= 0
    #连接超时时间(毫秒)
    spring.redis.timeout=1800000
    #连接池最大连接数(使用负值表示没有限制)
    spring.redis.lettuce.pool.max-active=20
    #最大阻塞等待时间(负数表示没限制)
    spring.redis.lettuce.pool.max-wait=-1
    #连接池中的最大空闲连接
    spring.redis.lettuce.pool.max-idle=5
    #连接池中的最小空闲连接
    spring.redis.lettuce.pool.min-idle=0
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    3、 添加redis配置类
    package com.yyds.sprint_boot_redis.config;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.cache.CacheManager;
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.cache.RedisCacheConfiguration;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.RedisSerializationContext;
    import org.springframework.data.redis.serializer.RedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    import java.time.Duration;
    
    @EnableCaching
    @Configuration
    public class RedisConfig extends CachingConfigurerSupport {
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            RedisSerializer<String> redisSerializer = new StringRedisSerializer();
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper om = new ObjectMapper();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(om);
            template.setConnectionFactory(factory);
    
            //key序列化方式
            template.setKeySerializer(redisSerializer);
            //value序列化
            template.setValueSerializer(jackson2JsonRedisSerializer);
            //value hashmap序列化
            template.setHashValueSerializer(jackson2JsonRedisSerializer);
    
            return template;
        }
    
        @Bean
        public CacheManager cacheManager(RedisConnectionFactory factory) {
            RedisSerializer<String> redisSerializer = new StringRedisSerializer();
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    
            //解决查询缓存转换异常的问题
            ObjectMapper om = new ObjectMapper();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(om);
    
            // 配置序列化(解决乱码的问题),过期时间600秒
            RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofSeconds(600))
                    .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                    .disableCachingNullValues();
            RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                    .cacheDefaults(config)
                    .build();
            return cacheManager;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    4、 测试
    package com.yyds.sprint_boot_redis.controller;
    
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/redis")
    public class RedisController {
    
        @Autowired
        RedisTemplate redisTemplate;
    
        @GetMapping("/test")
        public String testRedis(){
            // 向redis中设置值
            redisTemplate.opsForValue().set("k1", "v1");
            // 从redis中获取值
            String res = (String)redisTemplate.opsForValue().get("k1");
            return res;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    在这里插入图片描述

  • 相关阅读:
    Java注解-最通俗易懂的讲解
    前端工程化精讲第十二课 打包提效:如何为 Webpack 打包阶段提速?
    包装类知识点
    【Linux基础】第31讲 Linux用户和用户组权限控制命令(三)
    nginx配置参数详细解析
    AQS 框架中 setState() 和 setExclusiveOwnerThread() 方法顺序问题
    JS奇淫技巧:一行赋值语句,能玩出多少花样?
    C++基础篇考题
    庆金秋贺国庆 | 实验必备「取样一本通•植物篇」包邮免费送!
    【2023研电赛】安谋科技企业命题三等奖作品: 短临天气预报AI云图分析系统
  • 原文地址:https://blog.csdn.net/qq_44665283/article/details/128164947