• 【Redis】SSM整合Redis&注解式缓存的使用


    一、SSM整合Redis

    1.1.pom配置

    
    
    <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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0modelVersion>
    
      <groupId>org.examplegroupId>
      <artifactId>ssm2artifactId>
      <version>1.0-SNAPSHOTversion>
      <packaging>warpackaging>
    
      <name>ssm2 Maven Webappname>
      
      <url>http://www.example.comurl>
    
      <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>
        <maven.compiler.plugin.version>3.7.0maven.compiler.plugin.version>
    
        
        
        <spring.version>5.0.2.RELEASEspring.version>
        
        <mybatis.version>3.4.5mybatis.version>
        
        <mysql.version>5.1.44mysql.version>
        
        <pagehelper.version>5.1.2pagehelper.version>
        
        <mybatis.spring.version>1.3.1mybatis.spring.version>
        
        <commons.dbcp2.version>2.1.1commons.dbcp2.version>
        <commons.pool2.version>2.4.3commons.pool2.version>
        
        <log4j2.version>2.9.1log4j2.version>
        
        <junit.version>4.12junit.version>
        <servlet.version>4.0.0servlet.version>
        <lombok.version>1.18.2lombok.version>
    
        <ehcache.version>2.10.0ehcache.version>
        <slf4j-api.version>1.7.7slf4j-api.version>
    
        <redis.version>2.9.0redis.version>
        <redis.spring.version>1.7.1.RELEASEredis.spring.version>
      properties>
    
      <dependencies>
        
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-contextartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-ormartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-txartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-aspectsartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-webartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-testartifactId>
          <version>${spring.version}version>
        dependency>
    
        
        <dependency>
          <groupId>org.mybatisgroupId>
          <artifactId>mybatisartifactId>
          <version>${mybatis.version}version>
        dependency>
        
        <dependency>
          <groupId>mysqlgroupId>
          <artifactId>mysql-connector-javaartifactId>
          <version>${mysql.version}version>
        dependency>
        
        <dependency>
          <groupId>com.github.pagehelpergroupId>
          <artifactId>pagehelperartifactId>
          <version>${pagehelper.version}version>
        dependency>
        
        <dependency>
          <groupId>org.mybatisgroupId>
          <artifactId>mybatis-springartifactId>
          <version>${mybatis.spring.version}version>
        dependency>
    
        
        <dependency>
          <groupId>org.apache.commonsgroupId>
          <artifactId>commons-dbcp2artifactId>
          <version>${commons.dbcp2.version}version>
        dependency>
        <dependency>
          <groupId>org.apache.commonsgroupId>
          <artifactId>commons-pool2artifactId>
          <version>${commons.pool2.version}version>
        dependency>
    
        
        
        <dependency>
          <groupId>org.apache.logging.log4jgroupId>
          <artifactId>log4j-coreartifactId>
          <version>${log4j2.version}version>
        dependency>
        <dependency>
          <groupId>org.apache.logging.log4jgroupId>
          <artifactId>log4j-apiartifactId>
          <version>${log4j2.version}version>
        dependency>
        
        <dependency>
          <groupId>org.apache.logging.log4jgroupId>
          <artifactId>log4j-webartifactId>
          <version>${log4j2.version}version>
        dependency>
    
        
        <dependency>
          <groupId>junitgroupId>
          <artifactId>junitartifactId>
          <version>${junit.version}version>
          <scope>testscope>
        dependency>
        <dependency>
          <groupId>javax.servletgroupId>
          <artifactId>javax.servlet-apiartifactId>
          <version>${servlet.version}version>
          <scope>providedscope>
        dependency>
        <dependency>
          <groupId>org.projectlombokgroupId>
          <artifactId>lombokartifactId>
          <version>${lombok.version}version>
          <scope>providedscope>
        dependency>
    
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-webmvcartifactId>
          <version>${spring.version}version>
        dependency>
    
        
        <dependency>
          <groupId>javax.servlet.jspgroupId>
          <artifactId>javax.servlet.jsp-apiartifactId>
          <version>2.3.3version>
        dependency>
        <dependency>
          <groupId>jstlgroupId>
          <artifactId>jstlartifactId>
          <version>1.2version>
        dependency>
        <dependency>
          <groupId>taglibsgroupId>
          <artifactId>standardartifactId>
          <version>1.1.2version>
        dependency>
    
        <dependency>
          <groupId>commons-fileuploadgroupId>
          <artifactId>commons-fileuploadartifactId>
          <version>1.3.3version>
        dependency>
    
    
        <dependency>
          <groupId>org.hibernategroupId>
          <artifactId>hibernate-validatorartifactId>
          <version>6.0.7.Finalversion>
        dependency>
    
    
        <dependency>
          <groupId>com.fasterxml.jackson.coregroupId>
          <artifactId>jackson-databindartifactId>
          <version>2.9.3version>
        dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.coregroupId>
          <artifactId>jackson-coreartifactId>
          <version>2.9.3version>
        dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.coregroupId>
          <artifactId>jackson-annotationsartifactId>
          <version>2.9.3version>
        dependency>
    
    
        <dependency>
          <groupId>org.apache.shirogroupId>
          <artifactId>shiro-coreartifactId>
          <version>1.3.2version>
        dependency>
    
        <dependency>
          <groupId>org.apache.shirogroupId>
          <artifactId>shiro-webartifactId>
          <version>1.3.2version>
        dependency>
    
        <dependency>
          <groupId>org.apache.shirogroupId>
          <artifactId>shiro-springartifactId>
          <version>1.3.2version>
        dependency>
    
        <dependency>
          <groupId>net.sf.ehcachegroupId>
          <artifactId>ehcacheartifactId>
          <version>${ehcache.version}version>
        dependency>
    
        
        <dependency>
          <groupId>org.slf4jgroupId>
          <artifactId>slf4j-apiartifactId>
          <version>${slf4j-api.version}version>
        dependency>
        <dependency>
          <groupId>org.slf4jgroupId>
          <artifactId>jcl-over-slf4jartifactId>
          <version>${slf4j-api.version}version>
          <scope>runtimescope>
        dependency>
    
        
        <dependency>
          <groupId>org.apache.logging.log4jgroupId>
          <artifactId>log4j-slf4j-implartifactId>
          <version>${log4j2.version}version>
        dependency>
    
        <dependency>
          <groupId>redis.clientsgroupId>
          <artifactId>jedisartifactId>
          <version>${redis.version}version>
        dependency>
        <dependency>
          <groupId>org.springframework.datagroupId>
          <artifactId>spring-data-redisartifactId>
          <version>${redis.spring.version}version>
        dependency>
      dependencies>
    
      <build>
        <finalName>ssm2finalName>
        <resources>
          
          <resource>
            <directory>src/main/javadirectory>
            <includes>
              <include>**/*.xmlinclude>
            includes>
          resource>
          
          <resource>
            <directory>src/main/resourcesdirectory>
            <includes>
              <include>*.propertiesinclude>
              <include>*.xmlinclude>
            includes>
          resource>
        resources>
        <pluginManagement>
          <plugins>
            <plugin>
              <groupId>org.apache.maven.pluginsgroupId>
              <artifactId>maven-compiler-pluginartifactId>
              <version>${maven.compiler.plugin.version}version>
              <configuration>
                <source>${maven.compiler.source}source>
                <target>${maven.compiler.target}target>
                <encoding>${project.build.sourceEncoding}encoding>
              configuration>
            plugin>
            <plugin>
              <groupId>org.mybatis.generatorgroupId>
              <artifactId>mybatis-generator-maven-pluginartifactId>
              <version>1.3.2version>
              <dependencies>
                
                <dependency>
                  <groupId>mysqlgroupId>
                  <artifactId>mysql-connector-javaartifactId>
                  <version>${mysql.version}version>
                dependency>
              dependencies>
              <configuration>
                <overwrite>trueoverwrite>
              configuration>
            plugin>
    
            <plugin>
              <artifactId>maven-clean-pluginartifactId>
              <version>3.1.0version>
            plugin>
            
            <plugin>
              <artifactId>maven-resources-pluginartifactId>
              <version>3.0.2version>
            plugin>
            <plugin>
              <artifactId>maven-compiler-pluginartifactId>
              <version>3.8.0version>
            plugin>
            <plugin>
              <artifactId>maven-surefire-pluginartifactId>
              <version>2.22.1version>
            plugin>
            <plugin>
              <artifactId>maven-war-pluginartifactId>
              <version>3.2.2version>
            plugin>
            <plugin>
              <artifactId>maven-install-pluginartifactId>
              <version>2.5.2version>
            plugin>
            <plugin>
              <artifactId>maven-deploy-pluginartifactId>
              <version>2.8.2version>
            plugin>
          plugins>
        pluginManagement>
      build>
    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
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350

    注意:resources的配置必须涵盖读取.properties结尾的文件

    1.2.配置文件spring-redis.xml

    这个配置文件的作用主要用于配置数据源和连接工厂还有配置序列化的用途
    redis.properties

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

    spring-redis.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:cache="http://www.springframework.org/schema/cache"
           xsi:schemaLocation="http://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/cache
           http://www.springframework.org/schema/cache/spring-cache.xsd">
    
        
        
    
        
        <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
            
            <property name="maxIdle" value="${redis.maxIdle}"/>
            
            <property name="maxTotal" value="${redis.maxTotal}"/>
            
            <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
            
            <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
            
            <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
            
            <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
            
            <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
            
            <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
        bean>
    
        
        <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
              destroy-method="destroy">
            <property name="poolConfig" ref="poolConfig"/>
            
            <property name="hostName" value="${redis.hostName}"/>
            
            <property name="port" value="${redis.port}"/>
            
            <property name="password" value="${redis.password}"/>
            
            <property name="timeout" value="${redis.timeout}"/>
        bean>
    
        
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory" ref="connectionFactory"/>
            
            <property name="keySerializer">
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
            property>
            <property name="valueSerializer">
                <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
            property>
            <property name="hashKeySerializer">
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
            property>
            <property name="hashValueSerializer">
                <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
            property>
            
            <property name="enableTransactionSupport" value="true"/>
        bean>
    
        
        <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
            <constructor-arg name="redisOperations" ref="redisTemplate"/>
            
            <property name="defaultExpiration" value="${redis.expiration}"/>
            
            <property name="usePrefix" value="true"/>
            
            <property name="cachePrefix">
                <bean class="org.springframework.data.redis.cache.DefaultRedisCachePrefix">
                    <constructor-arg index="0" value="-cache-"/>
                bean>
            property>
        bean>
    
        
        <bean id="cacheKeyGenerator" class="com.zking.ssm.redis.CacheKeyGenerator">bean>
    
        
        <cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/>
    beans>
    
    • 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

    1.3.修改applicationContext.xml

    如果spring配置文件中需要配置两个及以上的properties文件则需要在applicationContext.xml中进行配置处理,否则会出现覆盖的情况。

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://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">
        
        <bean id="propertyConfigurer"
              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
            <property name="ignoreResourceNotFound" value="true" />
            <property name="locations">
                <list>
                    <value>classpath:jdbc.propertiesvalue>
                    <value>classpath:redis.propertiesvalue>
                list>
            property>
        bean>
     
    
        <import resource="applicationContext-mybatis.xml">import>
        <import resource="spring-redis.xml">import>
        <import resource="applicationContext-shiro.xml">import>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    1.4.配置redis的key生成策略

    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 key
        public static final int NO_PARAM_KEY = 0;
        public static final int NULL_PARAM_KEY = 53;
    
        @Override
        public 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和eqauls
                        key.append(param.hashCode());
                    }
                    count++;
                }
            }
    
            String finalKey = key.toString();
    //        IEDA要安装lombok插件
            log.debug("using cache key={}", finalKey);
            return finalKey;
        }
    }
    
    
    • 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

    这段代码实现了一个自定义的缓存键生成器,用于生成缓存的键值。让我们逐行分析一下代码的逻辑:

    导入所需的包: java import lombok.extern.slf4j.Slf4j; import
    org.springframework.cache.interceptor.KeyGenerator; import
    org.springframework.util.ClassUtils; 这些包提供了日志记录功能和用于操作类和对象的工具类。

    声明了一个日志记录器: java @Slf4j 这是Lombok库提供的注解,用于自动生成日志记录器。

    创建一个名为CacheKeyGenerator的类,并实现了KeyGenerator接口: java public class
    CacheKeyGenerator implements KeyGenerator {
    … } 定义了两个常量作为特殊情况的缓存键: java public static final int NO_PARAM_KEY = 0; public static final int NULL_PARAM_KEY = 53; NO_PARAM_KEY代表没有参数的情况下的缓存键。 NULL_PARAM_KEY代表参数值为null的情况下的缓存键。
    实现了generate方法: java @Override public Object generate(Object target,
    Method method, Object… params) {
    StringBuilder key = new StringBuilder();
    key.append(target.getClass().getSimpleName()).append(“.”).append(method.getName()).append(“:”);
    // 根据参数的数量和类型生成缓存键

    return finalKey; } 该方法使用目标对象、方法和参数来生成缓存键,并返回最终的键值。

    生成缓存键的逻辑: 首先,使用StringBuilder创建一个字符串缓存对象key,并将目标对象和方法名添加到key中。
    然后判断参数的数量,如果参数数量为0,则将NO_PARAM_KEY添加到key中表示无参数的情况。
    如果参数数量不为0,则遍历参数数组,根据参数的类型和值生成 对应的缓存键。
    如果参数为null,则将NULL_PARAM_KEY添加到key中表示参数值为null的情况。
    如果参数是原始类型或包装类类型,或者是字符串类型,则直接将参数值添加到key中。 否则,对于其他类型的参数,将其哈希码作为缓存键的一部分。
    最后,将生成的最终缓存键转换为字符串,记录日志,并返回该键值。
    这段代码主要用于在Spring缓存中自定义生成缓存键,以便更加灵活地控制缓存的存储和获取。

    二、Redis的注解式开发及应用场景

    2.1.什么是Redis注解式

    Redis注解式是一种在Java应用中使用Redis进行缓存操作的方法。它通过在代码中使用注解的方式来简化和统一对Redis的操作。

    通常情况下,我们需要手动编写代码来连接Redis服务器、创建连接池、获取连接、执行Redis命令等操作。而使用Redis注解式则可以通过在方法上添加特定的注解来实现相应的Redis操作,从而减少了繁琐的手动操作,并且提供了更加便捷的开发体验。

    在使用Redis注解式时,可以使用不同的注解来标识不同的操作,例如:

    @Cacheable:表示将方法的返回值存储到Redis缓存中,在后续调用该方法时,若参数与之前的调用相同,则直接从缓存中获取结果,避免重复计算或查询数据库。
    @CachePut:表示将方法的返回值更新到Redis缓存中,无论是否已存在缓存数据,都会执行方法并将返回值存储到缓存中。
    @CacheEvict:表示清除Redis缓存中的某个或某些数据,可以在方法执行前、执行后或条件满足时清除缓存。
    其他自定义的注解:根据具体需求,也可以自行定义注解来实现更加灵活的Redis操作。
    使用Redis注解式可以有效地提高代码的可读性和简洁性,并且避免了手动处理与Redis相关的繁琐任务,提升了开发效率。但需要注意的是,在使用Redis注解式时,要确保正确配置和运行Redis服务器,并合理使用缓存策略,以避免数据不一致或缓存失效等问题。

    2.实列测试·

    package com.zking.ssm.biz;
     
    import com.zking.ssm.model.Clazz;
    import com.zking.ssm.util.PageBean;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.CachePut;
     
    import java.util.List;
    import java.util.Map;
     
    public interface ClazzBiz {
        @CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)
        int deleteByPrimaryKey(Integer cid);
     
        int insert(Clazz record);
     
        int insertSelective(Clazz record);
     
    //    xx=cache-cid:1
    //    key的作用改变原有的key生成规则
    //    @Cacheable(value = "xx",key = "'cid:'+#cid")
        @CachePut(value = "xx",key = "'cid:'+#cid",condition = "#cid > 6")
        Clazz selectByPrimaryKey(Integer cid);
     
        int updateByPrimaryKeySelective(Clazz record);
     
        int updateByPrimaryKey(Clazz record);
     
        List<Clazz> listPager(Clazz clazz, PageBean pageBean);
        List<Map> listMapPager(Clazz clazz, PageBean pageBean);
    }
    
    • 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

    ①Cacheable
    使用该注解会将查询结果放入Redis中下一次同样的查询就不会走数据库,而是走Redis.

    在这里插入图片描述
    调动了两次方法,只走了一次数据库。有一次走的是redis

    ②CachePut
    该注解会将查询结果放入Redis中,类似于更新操作,即每次不管缓存中有没有结果,都从数据库查找结果,并将结果更新到缓存,并返回结果

    @CachePut(value = “xx”,key = “‘cid:’+#cid”)
    Clazz selectByPrimaryKey(Integer cid);
    value:缓存位置的一段名称,不能为空
    key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL
    condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL
    allEntries:true表示清除value中的全部缓存,默认为false

    ③CacheEvict
    用来清除用在本方法或者类上的缓存数据

    @CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)
    int deleteByPrimaryKey(Integer cid);
    
    • 1
    • 2

    value:缓存位置的一段名称,不能为空

    三、Redis中的击穿、穿透、雪崩的三种场景

    下是对Redis中的击穿、穿透和雪崩三种场景的诉述以及可能的解决方案:

    击穿(Cache Breakdown):

    场景:当一个热门的缓存键在缓存过期或被移除后,大量的请求同时涌入数据库或后端系统,导致系统负载增加。
    解决方案:
    设置热门数据的永久缓存时间,避免过早失效。
    使用互斥锁/分布式锁,确保只有一个线程能够重新生成缓存,其他线程等待并使用已生成的缓存数据。
    引入缓存预加载机制,在缓存失效之前提前异步更新缓存,避免请求直接落到数据库。
    穿透(Cache Penetration):

    场景:恶意用户请求一个不存在于缓存和数据库中的数据,导致每个请求都需要查询数据库,浪费资源。
    解决方案:
    对于无效的请求,可以将其对应的空结果也缓存起来,设置较短的过期时间,避免频繁查询数据库。
    对于非法的请求参数,可以进行参数校验或者限流处理,拒绝无效的请求。
    使用布隆过滤器(Bloom Filter)过滤掉不存在的数据,减少对数据库的查询压力。
    雪崩(Cache Avalanche):

    场景:当缓存中大量键同时过期或者在某个时间段内失效,导致大量请求直接落到数据库或后端系统,引发系统崩溃。
    解决方案:
    设置缓存数据的随机过期时间,避免批量失效。
    使用多级缓存架构,如本地缓存 + 分布式缓存,降低单点故障风险。
    实施熔断机制,当缓存失效超过一定次数或比例时,暂时关闭对后端系统的访问,以保护后端系统免受高并发的冲击。
    针对关键数据,可以使用主从复制、集群等方式提高缓存系统的可用性和稳定性。

  • 相关阅读:
    网页优化(布局优化、图片优化)
    6种常见三维曲面的Three.js实现
    【二分查找生活应用】
    股票魔法师第二阶段趋势模板选股公式,寻找上涨趋势
    百度发布文心大模型4.0,百度搜索实现重构;AI报告2023
    SLCP(Social and Labor Convergence Project) 社会劳工整合项目
    ES6中的set与map
    基于springboot实现在线外卖平台系统项目【项目源码】计算机毕业设计
    ByteHouse MaterializedMySQL 增强优化
    stack 相关题目 day 1
  • 原文地址:https://blog.csdn.net/m0_74018330/article/details/134259953