抚顺 网站建设,无锡工程造价信息网,深圳装修设计公司排名,做外贸英语网站目录#xff1a;
目录
一#xff0c;SSM整合redis
二#xff0c;redis注解式缓存
三#xff0c;Redis中的缓存穿透、雪崩、击穿的原因以及解决方案#xff08;附图#xff09; 一#xff0c;SSM整合redis
1.原因#xff1a; 整合SSM和Redis可以提升系统的性能、可… 目录
目录
一SSM整合redis
二redis注解式缓存
三Redis中的缓存穿透、雪崩、击穿的原因以及解决方案附图 一SSM整合redis
1.原因 整合SSM和Redis可以提升系统的性能、可伸缩性和可靠性在分布式环境下更好地支持会话管理、消息队列和分布式锁等功能。 2.步骤可以参考SSM整合mysql
导入pom依赖在Maven中添加Redis的依赖 redis.version2.9.0/redis.version
redis.spring.version1.7.1.RELEASE/redis.spring.versiondependencygroupIdredis.clients/groupIdartifactIdjedis/artifactIdversion${redis.version}/version
/dependency
dependencygroupIdorg.springframework.data/groupIdartifactIdspring-data-redis/artifactIdversion${redis.spring.version}/version
/dependency 2.2.spring-redis.xml的相关配置
redis.properties redis.hostName127.0.0.1
redis.port6379
redis.password123456
redis.timeout10000
redis.maxIdle300
redis.maxTotal1000
redis.maxWaitMillis1000
redis.minEvictableIdleTimeMillis300000
redis.numTestsPerEvictionRun1024
redis.timeBetweenEvictionRunsMillis30000
redis.testOnBorrowtrue
redis.testWhileIdletrue
redis.expiration3600 spring-redis.xml ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxmlns:cachehttp://www.springframework.org/schema/cachexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/cachehttp://www.springframework.org/schema/cache/spring-cache.xsd!-- 1. 引入properties配置文件 --!--context:property-placeholder locationclasspath:redis.properties /--!-- 2. redis连接池配置--bean idpoolConfig classredis.clients.jedis.JedisPoolConfig!--最大空闲数--property namemaxIdle value${redis.maxIdle}/!--连接池的最大数据库连接数 --property namemaxTotal value${redis.maxTotal}/!--最大建立连接等待时间--property namemaxWaitMillis value${redis.maxWaitMillis}/!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)--property nameminEvictableIdleTimeMillis value${redis.minEvictableIdleTimeMillis}/!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3--property namenumTestsPerEvictionRun value${redis.numTestsPerEvictionRun}/!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1--property nametimeBetweenEvictionRunsMillis value${redis.timeBetweenEvictionRunsMillis}/!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个--property nametestOnBorrow value${redis.testOnBorrow}/!--在空闲时检查有效性, 默认false --property nametestWhileIdle value${redis.testWhileIdle}//bean!-- 3. redis连接工厂 --bean idconnectionFactory classorg.springframework.data.redis.connection.jedis.JedisConnectionFactorydestroy-methoddestroyproperty namepoolConfig refpoolConfig/!--IP地址 --property namehostName value${redis.hostName}/!--端口号 --property nameport value${redis.port}/!--如果Redis设置有密码 --property namepassword value${redis.password}/!--客户端超时时间单位是毫秒 --property nametimeout value${redis.timeout}//bean!-- 4. redis操作模板,使用该对象可以操作redishibernate课程中hibernatetemplete相当于session专门操作数据库。--bean idredisTemplate classorg.springframework.data.redis.core.RedisTemplateproperty nameconnectionFactory refconnectionFactory/!--如果不配置Serializer那么存储的时候缺省使用String如果用User类型存储那么会提示错误User cant cast to String --property namekeySerializerbean classorg.springframework.data.redis.serializer.StringRedisSerializer//propertyproperty namevalueSerializerbean classorg.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer//propertyproperty namehashKeySerializerbean classorg.springframework.data.redis.serializer.StringRedisSerializer//propertyproperty namehashValueSerializerbean classorg.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer//property!--开启事务 --property nameenableTransactionSupport valuetrue//bean!-- 5.配置缓存管理器 --bean idredisCacheManager classorg.springframework.data.redis.cache.RedisCacheManagerconstructor-arg nameredisOperations refredisTemplate/!--redis缓存数据过期时间单位秒--property namedefaultExpiration value${redis.expiration}/!--是否使用缓存前缀与cachePrefix相关--property nameusePrefix valuetrue/!--配置缓存前缀名称--property namecachePrefixbean classorg.springframework.data.redis.cache.DefaultRedisCachePrefixconstructor-arg index0 value-cache-//bean/property/bean!--6.配置缓存生成键名的生成规则--bean idcacheKeyGenerator classcom.zking.ssm.redis.CacheKeyGenerator/bean!--7.启用缓存注解功能--cache:annotation-driven cache-managerredisCacheManager key-generatorcacheKeyGenerator/
/beans 2.3.修改applicationContext.xml
如果spring配置文件中需要配置两个及以上的properties文件则需要在applicationContext.xml中进行配置处理否则会出现覆盖的情况。
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/context xmlns:txhttp://www.springframework.org/schema/txxmlns:aophttp://www.springframework.org/schema/aopxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd!--1. 引入外部多文件方式 --bean idpropertyConfigurerclassorg.springframework.beans.factory.config.PropertyPlaceholderConfigurerproperty namesystemPropertiesModeName valueSYSTEM_PROPERTIES_MODE_OVERRIDE /property nameignoreResourceNotFound valuetrue /property namelocationslistvalueclasspath:jdbc.properties/valuevalueclasspath:redis.properties/value/list/property/bean!-- 随着后续学习框架会越学越多不能将所有的框架配置放到同一个配制间否者不便于管理 --import resourceapplicationContext-mybatis.xml/importimport resourcespring-redis.xml/importimport resourceapplicationContext-shiro.xml/import
/beans 2.4.配置redis的key生成策略
CacheKeyGenerator.java
package com.zking.ssm.redis;import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.util.ClassUtils;import java.lang.reflect.Array;
import java.lang.reflect.Method;Slf4j
public class CacheKeyGenerator implements KeyGenerator {// custom cache keypublic static final int NO_PARAM_KEY 0;public static final int NULL_PARAM_KEY 53;Overridepublic Object generate(Object target, Method method, Object... params) {StringBuilder key new StringBuilder();key.append(target.getClass().getSimpleName()).append(.).append(method.getName()).append(:);if (params.length 0) {key.append(NO_PARAM_KEY);} else {int count 0;for (Object param : params) {if (0 ! count) {//参数之间用,进行分隔key.append(,);}if (param null) {key.append(NULL_PARAM_KEY);} else if (ClassUtils.isPrimitiveArray(param.getClass())) {int length Array.getLength(param);for (int i 0; i length; i) {key.append(Array.get(param, i));key.append(,);}} else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {key.append(param);} else {//Java一定要重写hashCode和eqaulskey.append(param.hashCode());}count;}}String finalKey key.toString();
// IEDA要安装lombok插件log.debug(using cache key{}, finalKey);return finalKey;}
} 二redis注解式缓存
关于什么是Redis注解式
注解式缓存是一种通过在方法上添加特定的注解来实现自动缓存的机制。在Java开发中我们可以使用Spring框架提供的Cacheable、CachePut和CacheEvict等注解来实现对Redis的缓存操作。 Cacheable注解 作用标记方法的返回值可以被缓存并且在下次调用该方法时会直接从缓存中获取结果而不会执行方法体内的逻辑。示例代码Cacheable(value myCache, key #id)
public User getUserById(String id) {// 从数据库或其他数据源获取用户信息的逻辑return user;
}解释以上代码表示将方法的返回值以键值对的形式缓存在名为myCache的缓存中缓存的key由参数id决定。 CachePut注解 作用标记方法的返回值需要更新缓存即每次调用方法都会执行方法体内的逻辑并将返回值存入缓存。示例代码 CachePut(value myCache, key #user.id)
public User updateUser(User user) {// 更新用户信息的逻辑return user;
}解释以上代码表示每次调用该方法都会执行方法体内的逻辑然后将返回值以键值对的形式存入名为myCache的缓存中。缓存的key由user.id决定。 CacheEvict注解 作用标记方法会清除缓存中的指定数据。示例代码CacheEvict(value myCache, key #id)
public void deleteUser(String id) {// 删除用户信息的逻辑
}解释以上代码表示调用该方法时会从名为myCache的缓存中移除key为参数id对应的缓存数据。
通过使用这些注解我们可以更加方便地实现对Redis的缓存操作减少了手动管理缓存的复杂性。但需要注意的是使用注解式缓存时需要确保被缓存的方法的输入参数和返回值类型是可序列化的以便在Redis中进行存储和读取。
此外还可以通过配置Spring框架的缓存管理器、缓存策略等来进一步优化和配置缓存行为。具体的配置和使用细节可以参考Spring框架的文档和教程。 三Redis中的缓存穿透、雪崩、击穿的原因以及解决方案附图 缓存穿透Cache Penetration 原因当请求查询一个不存在于缓存和数据库中的数据时每次查询都会直接访问数据库导致对数据库的频繁访问增加数据库负载。情景客户端发送大量的不可响应的请求比如发送一个id为-999的用户解决方案 布隆过滤器Bloom Filter用于判断请求的数据是否存在于缓存或数据库中。使用布隆过滤器可以快速过滤掉一部分不存在的数据避免对数据库的无效查询。空值缓存Null Object Caching将不存在的数据也缓存起来但设置一个较短的过期时间以便下次查询时可以从缓存中获取。 注意事项 使用空值作为缓存的时候key设置的过期时间不能太长防止占用太多redis资源 对空值缓存是一种被动的防御方式当遇到黑客暴力请求很多不存在的数据就需要写入大量的null值到Redis中可能导致Redis内存占用不足的情况 使用布隆过滤器可以在用户访问的时候判断该资源是否存在不存在则直接拒绝访问 布隆过滤器是有一定的误差所以一般需要配合一些接口流量的限制规定用户在一段时间内访问的频率、权限校验、黑名单等来解决缓存穿透的问题 缓存雪崩Cache Avalanche 原因当缓存中的大量数据同时过期或失效时所有请求都会直接访问数据库导致数据库压力骤增甚至导致数据库宕机。解决方案 随机过期时间Randomized Expiration为缓存中的数据设置随机的过期时间以避免大量数据同时过期。并发控制Concurrency Control使用分布式锁或互斥机制确保只有一个线程可以重新加载缓存数据避免重复查询。 缓存击穿Cache Miss 原因当某个热点数据过期或失效时大量请求同时涌入导致并发查询数据库增加数据库压力。解决方案 互斥锁Mutex Lock在缓存失效的情况下使用互斥锁来确保只有一个请求可以查询数据库并将查询结果进行缓存其他请求等待缓存更新后再获取数据。提前加载Preloading提前加载热点数据到缓存中并设置较长的过期时间以避免热点数据过期后被击穿。