• Redis相关知识


    目录

    一,Redis的命令操作

    1.Redis简介

    2.Redis安装(按步骤执行以下步骤即可)

    3.redis命令

    二,java代码操作Redis

    1.java连接Redis

    2.java操作Redis

    三,Spring注解式缓存Redis

    1.Spring整合Redis

    2.redis注解式缓存

    3.Redis击穿穿透以及雪崩

    击穿:高并发量的同时key失效,导致请求直接到达数据库;


    一,Redis的命令操作

    1.Redis简介

    Redis是一个开源(BSD许可),内存存储的数据结构服务器,可用作数据库,高速缓存和消息队列代理。
       它支持字符串、哈希表、列表、集合、有序集合,位图,hyperloglogs等数据类型。内置复制、Lua脚本、LRU收回、事务以及不同级别磁盘持久化功能,
       同时通过Redis Sentinel提供高可用,通过Redis Cluster提供自动分区

    学习网址:Redis 教程_w3cschool

    Redis用途:1. 数据库 2. 缓存
    集群:哨兵、主从、分片式   

    2.Redis安装(按步骤执行以下步骤即可)

    1.解压redis
    tar -zxvf redis-5.0.0.tar.gz -C /usr/local

    2.安装gcc
    yum install gcc

    3.编译redis
    cd /redis-5.0.0
    make

    4.检测安装情况
    make install

    5.修改redis.conf文件
    cp redis.conf redis_bak.conf
    将daemonize no 改为 daemonize yes

    6.启动redis
    ./redis-server ../redis.conf

    7.测试redis启动是否成功
    ./redis-cli
    ping

    附录
     Linux在文件中查找关键字
    vim xxx.conf
    先"/" 然后"关键字" 再enter;"n"指找下一个

    查看redis进程:
    ps -ef | grep redis
    yum install -y lsof
    lsof -i:6379
    杀掉redis进程:kill -9 进程pid

    以上为无密码链接,修改为有密码,并且外部访问的方式如下

    1.修改redis.conf
    注释:bind 127.0.0.1
    修改:requirepass 123456

    2.杀掉redis进程

    3.启动redis.conf的新配置
    ./src/redis-server redis.conf

    4.客户端redis-cli链接redis,重新测试
    ./src/redis-cli -h 127.0.0.1 -p 6379 -a 123456
    ping
    select 1

    5.redismanager链接测试成功

    3.redis命令

    set key          //保存
    set name zs
    set age 12
    set sex nan

    get key          //获取
    get name

    type key         //查看类型
    type age            //string 说明type返回的是键值对存储类型,而不是值存储类型

    keys *或keys key //查看所有或者指定的key
    keys *

    SETEX KEY_NAME TIMEOUT VALUE    // 给键值对设置过期时间
    setex zs 60 live

    ttl key    // 获取键值对剩余的存活时间
    ttl zs

    Redis哈希(Hash)

    Redis hash 是一个string类型的field和value的映射表,hash特别适合用于存储对象。

    1. hset key field1 value1 [field2 value2] 同时将多个field-value设置到哈希表key中
    2. hset user name zs age 12 sex nv
    3. hget key field #获取指定的字段值
    4. hget user age
    5. hdel key field #删除指定的字段值
    6. hdel user age
    7. hgetall key #查询指定key的所有字段
    8. hgetall user
    9. hexists key field #查询指定key中的字段是否存在
    10. hexists user name
    11. hlen key #获取指定key中的长度
    12. hlen user

    Redis列表(List)

    Redis列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素到列表的头部(左边)或者尾部(右边)

    1. lpush key value1 value2 value3 #将一个或多个值插入到列表头部
    2. lpush en a b c d e f g
    3. llen key #获取列表的长度
    4. llen en
    5. lindex key index #根据索引获取列表中的元素
    6. lindex en 1 #返回f,说明下标从0开始,同时先进后出
    7. lrange key start sop #查看指定范围内的元素
    8. lrange en 1 3 #返回fed,说明下标从0开始,同时先进后出

    Redis集合(Set)

    Redis 的 Set 是 String 类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据

    1. sadd key value1 [value2] #向集合添加一个或多个元素
    2. sadd hobby lanqiu zuqiu bingpangqiu zhuoqiu
    3. scard key #获取集合中的元素数量
    4. scard hobby
    5. exists key #是否存在
    6. exists hobby

    有序集合(sort set)

    参考网址:Redis 有序集合(sorted set)_w3cschool

    二,java代码操作Redis

    1.java连接Redis

    首先在编码前我们先将环境搭好,导入相关依赖

    1. <groupId>redis.clientsgroupId>
    2. <artifactId>jedisartifactId>
    3. <version>2.9.0version>

    其次就是相关连接,Jedis jedis = new Jedis("192.168.230.129", 6379);这里如果是自身有云服务器的话直接连接服务器

    这边由于本人窘迫连接的地址为虚拟机上的地址

    1. Jedis jedis = new Jedis("192.168.195.139", 6379);
    2. jedis.auth("123456");
    3. System.out.println(jedis.ping());
    4. jedis.select(1);

    2.java操作Redis

    Redis字符串(String)

            set key          //保存
            jedis.set("string_name","wangwu");


            get key          //获取
            System.out.println(jedis.get("string_name"));


            type key         //查看类型
            System.out.println(jedis.type("string_name"));


            keys * 或keys key //查看所有或者指定的key
            System.out.println(jedis.keys("*"));


            SETEX KEY_NAME TIMEOUT VALUE    // 给键值对设置过期时间
            jedis.setex("string_zs",30,"活着");


            ttl key    // 获取键值对剩余的存活时间
            System.out.println(jedis.ttl("string_zs"));

     Redis哈希(Hash)

    hset key field1 value1 [field2 value2]  #同时将多个field-value设置到哈希表key中
    jedis.hset("java_user","name","zs");
    jedis.hset("java_user","sex","男");
    jedis.hset("java_user","age","12");

        hget key field                          #获取指定的字段值
    System.out.println(jedis.hget("java_user", "sex"));

       hdel key field                          #删除指定的字段值
    jedis.hdel("java_user","sex");

       hgetall key                             #查询指定key的所有字段
    Map java_user_map = jedis.hgetAll("java_user");
    System.out.println(java_user_map);

        hexists key field                       #查询指定key中的字段是否存在
    Boolean java_user = jedis.hexists("java_user","sex");
    System.out.println(java_user);

        hlen key                                #获取指定key中的长度
    Long java_user_len = jedis.hlen("java_user");
    System.out.println(java_user_len);

    Redis列表(List)

            lpush key value1 value2 value3          #将一个或多个值插入到列表头部
    jedis.lpush("java_hobby", "篮球", "足球", "羽毛球");


            llen key                                #获取列表的长度
    Long java_hobby_len = jedis.llen("java_hobby");
    System.out.println(java_hobby_len);


            lindex key index                        #根据索引获取列表中的元素
    System.out.println(jedis.lindex("java_hobby", 0));


            lrange key start sop                    #查看指定范围内的元素
    System.out.println(jedis.lrange("java_hobby", 0, 1));

    Redis集合(Set)

    //        # sadd key value1 [value2]                #向集合添加一个或多个元素
    jedis.sadd("java_set_user","张三","李四","王五","张三丰");


    //        # scard key                               #获取集合中的元素数量
    System.out.println(jedis.scard("java_set_user"));


    //        # exists key                              #是否存在
    System.out.println(jedis.exists("java_set_user"));

    三,Spring注解式缓存Redis

    1.Spring整合Redis

    导入相关依赖

    1. version>2.9.0version>
    2. <redis.spring.version>1.7.1.RELEASEredis.spring.version>
    3. <dependency>
    4. <groupId>redis.clientsgroupId>
    5. <artifactId>jedisartifactId>
    6. <version>${redis.version}version>
    7. dependency>
    8. <dependency>
    9. <groupId>org.springframework.datagroupId>
    10. <artifactId>spring-data-redisartifactId>
    11. <version>${redis.spring.version}version>
    12. dependency>

    Redis-properties(连接Redis相关)

    1. redis.hostName=192.168.195.139
    2. redis.port=6379
    3. redis.password=123456
    4. redis.timeout=10000
    5. redis.maxIdle=300
    6. redis.maxTotal=1000
    7. redis.maxWaitMillis=1000
    8. redis.minEvictableIdleTimeMillis=300000
    9. redis.numTestsPerEvictionRun=1024
    10. redis.timeBetweenEvictionRunsMillis=30000
    11. redis.testOnBorrow=true
    12. redis.testWhileIdle=true
    13. redis.expiration=3600

    spring-redis.xml文件(相关配置)

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:cache="http://www.springframework.org/schema/cache"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring-beans.xsd
    8. http://www.springframework.org/schema/context
    9. http://www.springframework.org/schema/context/spring-context.xsd
    10. http://www.springframework.org/schema/cache
    11. http://www.springframework.org/schema/cache/spring-cache.xsd">
    12. <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    13. <property name="maxIdle" value="${redis.maxIdle}"/>
    14. <property name="maxTotal" value="${redis.maxTotal}"/>
    15. <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
    16. <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
    17. <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
    18. <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
    19. <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
    20. <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
    21. bean>
    22. <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
    23. destroy-method="destroy">
    24. <property name="poolConfig" ref="poolConfig"/>
    25. <property name="hostName" value="${redis.hostName}"/>
    26. <property name="port" value="${redis.port}"/>
    27. <property name="password" value="${redis.password}"/>
    28. <property name="timeout" value="${redis.timeout}"/>
    29. bean>
    30. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
    31. <property name="connectionFactory" ref="connectionFactory"/>
    32. <property name="keySerializer">
    33. <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    34. property>
    35. <property name="valueSerializer">
    36. <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
    37. property>
    38. <property name="hashKeySerializer">
    39. <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    40. property>
    41. <property name="hashValueSerializer">
    42. <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
    43. property>
    44. <property name="enableTransactionSupport" value="true"/>
    45. bean>
    46. <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
    47. <constructor-arg name="redisOperations" ref="redisTemplate"/>
    48. <property name="defaultExpiration" value="${redis.expiration}"/>
    49. <property name="usePrefix" value="true"/>
    50. <property name="cachePrefix">
    51. <bean class="org.springframework.data.redis.cache.DefaultRedisCachePrefix">
    52. <constructor-arg index="0" value="-cache-"/>
    53. bean>
    54. property>
    55. bean>
    56. <bean id="cacheKeyGenerator" class="com.zking.ssm.redis.CacheKeyGenerator">bean>
    57. <cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/>
    58. beans>

    注意:redis.properties与jdbc.properties在与Spring做整合时会发生冲突;所以引入配置文件的地方要放到SpringContext.xml中

    SpringContext.xml配置如下

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    5. <bean id="propertyConfigurer"
    6. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    7. <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    8. <property name="ignoreResourceNotFound" value="true" />
    9. <property name="locations">
    10. <list>
    11. <value>classpath:jdbc.propertiesvalue>
    12. <value>classpath:redis.propertiesvalue>
    13. list>
    14. property>
    15. bean>
    16. <import resource="applicationContext-mybatis.xml">import>
    17. <import resource="applicationContext-ehcache.xml">import>
    18. <import resource="applicationContext-redis.xml">import>
    19. <import resource="applicationContext-shiro.xml"/>
    20. beans>

    2.redis注解式缓存

    @Cacheable

    配置在方法或类上,作用:本方法执行后,先去缓存看有没有数据,如果没有,从数据库中查找出来,给缓存中存一份,返回结果, 下次本方法执行,在缓存未过期情况下,先在缓存中查找,有的话直接返回,没有的话从数据库查找

    value:缓存位置的一段名称,不能为空
    key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL
    condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL 

    1. @RunWith(SpringJUnit4ClassRunner.class)
    2. @ContextConfiguration(locations={"classpath:applicationContext.xml"})

    @Cacheable 的测试代码

    1. @Cacheable(value = "user-clz",key = "'clz:'+#cid",condition = "#cid < 5")
    2. Clazz selectByPrimaryKey(Integer cid);

    代码如下

    1. public void test1(){
    2. 测试 Cacheable 中的value,以及缓存的应用体现
    3. System.out.println(clazzBiz.selectByPrimaryKey(1));
    4. System.out.println("======================================");
    5. System.out.println(clazzBiz.selectByPrimaryKey(1));
    6. 测试 Cacheable 中的 key
    7. System.out.println(clazzBiz.selectByPrimaryKey(3));
    8. System.out.println("======================================");
    9. System.out.println(clazzBiz.selectByPrimaryKey(3));
    10. 测试 Cacheable 中的 condition
    11. System.out.println(clazzBiz.selectByPrimaryKey(4));
    12. System.out.println("======================================");
    13. System.out.println(clazzBiz.selectByPrimaryKey(4));
    14. }

    测试结果为:redis中有数据,则访问redis;如果没有数据,则访问MySQL;

    @CachePut

    类似于更新操作,即每次不管缓存中有没有结果,都从数据库查找结果,并将结果更新到缓存,并返回结果

    value    缓存的名称,在 spring 配置文件中定义,必须指定至少一个
    key    缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
    condition    缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存

    测试代码

    1. @CachePut(value = "user-clz-put")
    2. Clazz selectByPrimaryKey(Integer cid);
    1. @Test
    2. public void test2(){
    3. 测试 Cacheput 中的 key
    4. System.out.println(clazzBiz.selectByPrimaryKey(4));
    5. System.out.println("======================================");
    6. System.out.println(clazzBiz.selectByPrimaryKey(4));
    7. }

    测试结果为:只存不取

    @CacheEvict

    用来清除用在本方法或者类上的缓存数据(用在哪里清除哪里)

    value:缓存位置的一段名称,不能为空
    key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL
    condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL
    allEntries:true表示清除value中的全部缓存,默认为false

    测试代码

    1. @CacheEvict(value = "user-clz-put",key = "'clz:'+#cid") 删除指定的缓存数据
    2. @CacheEvict(value = "user-clz-put",allEntries = true) // 删除以 user-clz-put开头的 缓存
    3. int deleteByPrimaryKey(Integer cid);
    1. @Test
    2. public void test3(){
    3. 测试 CacheEvict 中的 key
    4. clazzBiz.deleteByPrimaryKey(2);
    5. }

    测试结果为:可以配置删除指定缓存数据,也可以删除符合规则的所有缓存数据

    3.Redis击穿穿透以及雪崩

    击穿:高并发量的同时key失效,导致请求直接到达数据库;

    设置锁
    1.获取 Redis 锁,如果没有获取到,则回到任务队列继续排队
    2.获取到锁,从数据库拉取数据并放入缓存中
    3.释放锁,其他请求从缓存中拿到数据

    限流:请求redis之前做流量削峰

     穿透: 很多请求都在访问数据库一定不存在的数据,造成请求将缓存和数据库都穿透的情况。

    规则排除
    可以增加一些参数检验。例如数据库数据 id 一般都是递增的,如果请求 id = -10 这种参数,势必绕过Redis。避免这种情况,可以对用户真实性检验等操作。

    null值填充
    当缓存穿透时,redis存入一个类似null的值,下次访问则直接缓存返回空,当数据库中存在该数据的值则需要把redis存在的null值清除并载入新值,此方案不能解决频繁随机不规则的key请求。

     雪崩 雪崩和击穿类似,不同的是击穿是一个热点 Key 某时刻失效,而雪崩是大量的热点 Key 在一瞬间失效 。

    给不同的热点key设置不同的缓存策略

  • 相关阅读:
    我最喜欢的白版应用,AI加持的新功能开源!强烈推荐
    Python asyncio 库源码分析
    Java开发之多线程包含代码调试【面试篇 持续更新】
    Spring Boot 2.x源码系列【4】启动流程深入解析之启动监听器
    Springboot毕设项目系部期末考务管理系统ftt6kjava+VUE+Mybatis+Maven+Mysql+sprnig)
    全球化系统设计:多时区处理
    TDK | CeraLink 电容器快速切换逆变器的革新
    HTML+CSS大作业【传统文化艺术耍牙15页】学生个人网页设计作品
    关于将ffmpeg教程(tutorial01)移植到android ffmpeg上面的实现过程
    谱图论:Laplacian算子及其谱性质
  • 原文地址:https://blog.csdn.net/weixin_66202611/article/details/127664122