Redis integrates Spring annotation cache with SSM

Table of contents

1. Integration

1.1. Integrated applications

1.1.1.pom configuration

1.1.2.Required configuration

2. Annotation development and application scenarios

2.1. @Cacheable

2.2. @CachePut 

2.3. @CacheEvict

2.4. Summary

3. Redis’ breakdown and penetration avalanche

                That’s it for today! ! Hope this helps! !​ 


1. Integration

1.1. Integrated applications

1.1.1.pom configuration

Add Redis dependency in the project's pom.xml file

 The following are all imported dependencies: 

<?xml version="1.0" encoding="UTF-8"?>
 
<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.0</modelVersion>
 
  <groupId>org.example</groupId>
  <artifactId>ssm2</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
 
  <name>ssm2 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>
 
    <!--添加jar包依赖-->
    <!--1.spring 5.0.2.RELEASE相关-->
    <spring.version>5.0.2.RELEASE</spring.version>
    <!--2.mybatis相关-->
    <mybatis.version>3.4.5</mybatis.version>
    <!--mysql-->
    <mysql.version>5.1.44</mysql.version>
    <!--pagehelper分页jar依赖-->
    <pagehelper.version>5.1.2</pagehelper.version>
    <!--mybatis与spring集成jar依赖-->
    <mybatis.spring.version>1.3.1</mybatis.spring.version>
    <!--3.dbcp2连接池相关 druid-->
    <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
    <commons.pool2.version>2.4.3</commons.pool2.version>
    <!--4.log日志相关-->
    <log4j2.version>2.9.1</log4j2.version>
    <!--5.其他-->
    <junit.version>4.12</junit.version>
    <servlet.version>4.0.0</servlet.version>
    <lombok.version>1.18.2</lombok.version>
 
    <ehcache.version>2.10.0</ehcache.version>
    <slf4j-api.version>1.7.7</slf4j-api.version>
 
    <redis.version>2.9.0</redis.version>
    <redis.spring.version>1.7.1.RELEASE</redis.spring.version>
  </properties>
 
  <dependencies>
    <!--1.spring相关-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
 
    <!--2.mybatis相关-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!--pagehelper分页插件jar包依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>${pagehelper.version}</version>
    </dependency>
    <!--mybatis与spring集成jar包依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>
 
    <!--3.dbcp2连接池相关-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>${commons.dbcp2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
      <version>${commons.pool2.version}</version>
    </dependency>
 
    <!--4.log日志相关依赖-->
    <!--核心log4j2jar包-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--web工程需要包含log4j-web,非web工程不需要-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-web</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
 
    <!--5.其他-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
    </dependency>
 
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
 
    <!-- jsp依赖-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
 
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>
 
<!--    做服务端参数校验 JSR303 的jar包依赖 -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>6.0.7.Final</version>
    </dependency>
 
<!--    用来SpringMVC支持json数据转换-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.3</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.3</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.3</version>
    </dependency>
 
<!--    shiro相关依赖 -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>1.3.2</version>
    </dependency>
 
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-web</artifactId>
      <version>1.3.2</version>
    </dependency>
 
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>1.3.2</version>
    </dependency>
 
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
      <version>${ehcache.version}</version>
    </dependency>
 
    <!-- slf4j核心包 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j-api.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>${slf4j-api.version}</version>
      <scope>runtime</scope>
    </dependency>
 
    <!--用于与slf4j保持桥接 -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
 
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>${redis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>${redis.spring.version}</version>
    </dependency>
  </dependencies>
 
  <build>
    <finalName>ssm2</finalName>
    <resources>
      <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>*.properties</include>
          <include>*.xml</include>
        </includes>
      </resource>
    </resources>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <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.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.3.2</version>
          <dependencies>
            <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
            <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>${mysql.version}</version>
            </dependency>
          </dependencies>
          <configuration>
            <overwrite>true</overwrite>
          </configuration>
        </plugin>
 
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

1.1.2.Required configuration

Create a spring-readis.xml in the SSM project, configure Redis connection information, configure data source, configure serializer and redis Key generation strategy, configure RedisTemplate.

Create redis.properties Write data connection information, including host name, port number, password, etc.

redis.hostName=localhost
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

  Create spring-redis.xml configuration file and configure the following in it

Configuration of redis connection pool

 <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}"/>
        <!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)-->
        <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
        <!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3-->
        <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
        <!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1-->
        <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
        <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个-->
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
        <!--在空闲时检查有效性, 默认false  -->
        <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
    </bean>

Configure redis connection factory

    <!-- 3. redis连接工厂 -->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          destroy-method="destroy">
        <property name="poolConfig" ref="poolConfig"/>
        <!--IP地址 -->
        <property name="hostName" value="${redis.hostName}"/>
        <!--端口号  -->
        <property name="port" value="${redis.port}"/>
        <!--如果Redis设置有密码  -->
        <property name="password" value="${redis.password}"/>
        <!--客户端超时时间单位是毫秒  -->
        <property name="timeout" value="${redis.timeout}"/>
    </bean>

redis operation template

    <!-- 4. redis操作模板,使用该对象可以操作redis
        相当于session,专门操作数据库。
    -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!!  -->
        <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>

Configure cache manager

    <!--  5.配置缓存管理器  -->
    <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg name="redisOperations" ref="redisTemplate"/>
        <!--redis缓存数据过期时间单位秒-->
        <property name="defaultExpiration" value="${redis.expiration}"/>
        <!--是否使用缓存前缀,与cachePrefix相关-->
        <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>

Create CacheKeyGenerator.java Configure the generation rules for cache generated key names

package com.junlinyi.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;
    }
}

 Finally spring-redis.xml All configurations of the configuration file are as follows: 

<?xml version="1.0" encoding="UTF-8"?>
<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">
 
    <!-- 1. 引入properties配置文件 -->
    <!--<context:property-placeholder location="classpath:redis.properties" />-->
 
    <!-- 2. redis连接池配置-->
    <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}"/>
        <!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)-->
        <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
        <!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3-->
        <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
        <!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1-->
        <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
        <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个-->
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
        <!--在空闲时检查有效性, 默认false  -->
        <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
    </bean>
 
    <!-- 3. redis连接工厂 -->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          destroy-method="destroy">
        <property name="poolConfig" ref="poolConfig"/>
        <!--IP地址 -->
        <property name="hostName" value="${redis.hostName}"/>
        <!--端口号  -->
        <property name="port" value="${redis.port}"/>
        <!--如果Redis设置有密码  -->
        <property name="password" value="${redis.password}"/>
        <!--客户端超时时间单位是毫秒  -->
        <property name="timeout" value="${redis.timeout}"/>
    </bean>
 
    <!-- 4. redis操作模板,使用该对象可以操作redis
        相当于session,专门操作数据库。
    -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!!  -->
        <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>
 
    <!--  5.配置缓存管理器  -->
    <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg name="redisOperations" ref="redisTemplate"/>
        <!--redis缓存数据过期时间单位秒-->
        <property name="defaultExpiration" value="${redis.expiration}"/>
        <!--是否使用缓存前缀,与cachePrefix相关-->
        <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>
 
    <!--6.配置缓存生成键名的生成规则-->
    <bean id="cacheKeyGenerator" class="com.junlinyi.ssm.redis.CacheKeyGenerator"></bean>
 
    <!--7.启用缓存注解功能-->
    <cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/>
</beans>

 Create applicationContext-shiro.xml Configuration file 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <!--配置自定义的Realm-->
    <bean id="shiroRealm" class="com.junlinyi.ssm.shiro.MyRealm">
        <property name="userBiz" ref="userBiz" />
        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--以下三个配置告诉shiro将如何对用户传来的明文密码进行加密-->
        <property name="credentialsMatcher">
            <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!--指定hash算法为MD5-->
                <property name="hashAlgorithmName" value="md5"/>
                <!--指定散列次数为1024次-->
                <property name="hashIterations" value="1024"/>
                <!--true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存储-->
                <property name="storedCredentialsHexEncoded" value="true"/>
            </bean>
        </property>
    </bean>
 
    <!--注册安全管理器-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="sessionManager" ref="sessionManager"></property>
        <property name="realm" ref="shiroRealm" />
    </bean>
 
    <!--Shiro核心过滤器-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- Shiro的核心安全接口,这个属性是必须的 -->
        <property name="securityManager" ref="securityManager" />
        <!-- 身份验证失败,跳转到登录页面 -->
        <property name="loginUrl" value="/login"/>
        <!-- 身份验证成功,跳转到指定页面 -->
        <!--<property name="successUrl" value="/index.jsp"/>-->
        <!-- 权限验证失败,跳转到指定页面 -->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
        <!-- Shiro连接约束配置,即过滤链的定义 -->
        <property name="filterChainDefinitions">
            <value>
                <!--
                注:anon,authcBasic,auchc,user是认证过滤器
                    perms,roles,ssl,rest,port是授权过滤器
                -->
                <!--anon 表示匿名访问,不需要认证以及授权-->
                <!--authc表示需要认证 没有进行身份认证是不能进行访问的-->
                <!--roles[admin]表示角色认证,必须是拥有admin角色的用户才行-->
                /user/login=anon
                /user/updatePwd.jsp=authc
                /admin/*.jsp=roles[4]
                /user/teacher.jsp=perms[2]
                <!-- /css/**               = anon
                 /images/**            = anon
                 /js/**                = anon
                 /                     = anon
                 /user/logout          = logout
                 /user/**              = anon
                 /userInfo/**          = authc
                 /dict/**              = authc
                 /console/**           = roles[admin]
                 /**                   = anon-->
            </value>
        </property>
    </bean>
 
    <!-- Shiro生命周期,保证实现了Shiro内部lifecycle函数的bean执行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
 
 
    <!-- Session ID 生成器 -->
    <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator">
    </bean>
 
    <!--sessionDao自定义会话管理,针对Session会话进行CRUD操作-->
    <bean id="customSessionDao" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO">
        <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
    </bean>
 
    <!--会话监听器-->
    <bean id="shiroSessionListener" class="com.junlinyi.ssm.shiro.MySessionListener"/>
 
    <!--会话cookie模板-->
    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <!--设置cookie的name-->
        <constructor-arg value="shiro.session"/>
        <!--设置cookie有效时间 永不过期-->
        <property name="maxAge" value="-1"/>
        <!--设置httpOnly 防止xss攻击:cookie劫持-->
        <property name="httpOnly" value="true"/>
    </bean>
 
    <!--SessionManager会话管理器-->
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!--设置session会话过期时间 毫秒 2分钟=120000-->
        <property name="globalSessionTimeout" value="120000"/>
        <!--设置sessionDao-->
        <property name="sessionDAO" ref="customSessionDao"/>
        <!--设置间隔多久检查一次session的有效性 默认1分钟-->
        <property name="sessionValidationInterval" value="60000"/>
        <!--配置会话验证调度器-->
        <!--<property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>-->
        <!--是否开启检测,默认开启-->
        <!--<property name="sessionValidationSchedulerEnabled" value="true"/>-->
        <!--是否删除无效的session,默认开启-->
        <property name="deleteInvalidSessions" value="true"/>
        <!--配置session监听器-->
        <property name="sessionListeners">
            <list>
                <ref bean="shiroSessionListener"/>
            </list>
        </property>
        <!--会话Cookie模板-->
        <property name="sessionIdCookie" ref="sessionIdCookie"/>
        <!--取消URL后面的JSESSIONID-->
        <property name="sessionIdUrlRewritingEnabled" value="true"/>
    </bean>
</beans>

 Reference the above configuration file in the referenced configuration file, such as applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <!--1. 引入外部多文件方式 -->
    <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.properties</value>
                <value>classpath:redis.properties</value>
            </list>
        </property>
    </bean>
 
<!--  框架会越学越多,不能将所有的框架配置,放到同一个配制间,否者不便于管理  -->
    <import resource="applicationContext-mybatis.xml"></import>
    <import resource="spring-redis.xml"></import>
    <import resource="applicationContext-shiro.xml"></import>
</beans>

 The above are the basic configuration steps, which may vary depending on specific project requirements and framework versions. In actual applications, you can also configure Redis's cluster, sentinel mode, persistence and other functions as needed to improve the availability and reliability of the system.

2. Annotation development and application scenarios

2.1. @Cacheable

@Cacheable is an annotation in Spring Framework, used to declare that the return value of a method can be cached. This means that the return value of the method will be cached in memory so that subsequent calls can directly return the cached result without executing the method again.

Specifically,@Cacheable annotation functions as follows:

1. Cache results:When a method modified with the @Cacheable annotation is called, Spring will first check whether the return result of the method exists in the cache. If it already exists in the cache, the result in the cache will be returned directly without executing the code logic in the method body.

2. Cache key generation:@CacheableThe annotation can specify a cache key (key) to identify the data in the cache. By default, the cache key is composed of the method's parameters. If the method parameters are the same in two calls, the same cache key will be used and the results in the cache will be returned directly.

3. Cache management:@Cacheable annotation can be integrated with other cache management tools (such as Redis, Ehcache, etc.). By configuring the corresponding cache manager in the configuration file, the return results of the method can be stored in the specified cache for subsequent calls.

4. Cache invalidation:@CacheableThe annotation can also specify an expiration time (TTL) to control the validity period of the cache. When the cache validity period expires, the next time the method is called, the code logic in the method body will be re-executed and the new results will be stored in the cache.
Using the @Cacheable annotation can effectively reduce the number of accesses to the database or other resources and improve the system's response speed and concurrent processing capabilities. However, it should be noted that when using cache, you need to balance the consistency and real-time performance of the cache to avoid data inconsistency or expiration issues.

Commonly used properties and usage

The @Cacheable annotation has the following common attributes and usage functions:

 

value:Specifies the name of the cache, which is used to distinguish different cache spaces. The corresponding cache manager can be configured in the configuration file to decide in which cache space the cache will be stored. Multiple cache names can be specified, separated by commas.

key:Specifies the cache key, which is used to identify the data in the cache. By default, the cache key is composed of the method's parameters. The cache key can be specified using a SpEL expression, for example: @Cacheable(key = "#id"), where id is the parameter of the method.

condition:Specifies a SpEL expression to determine whether to perform a cache operation. The cache operation is only performed if the expression evaluates to true. For example: @Cacheable(condition = "#result != null"), which means that the cache operation will only be performed when the return result of the method is not empty.

unless:Specifies a SpEL expression to determine whether to perform cache operations. The cache operation is only performed if the expression evaluates to false. For example: @Cacheable(unless = "#result == null") means that the cache operation will not be performed only when the return result of the method is empty.

keyGenerator:Specifies a custom cache key generator used to generate cache keys. You can implement the KeyGenerator interface to customize the cache key generation logic.
Using the @Cacheable annotation can cache the return results of the method, improving the system's response speed and concurrent processing capabilities. You can have more granular control over your cache by specifying properties such as cache name, cache key, conditions, and key generators. At the same time, attention needs to be paid to balancing cache consistency and real-time performance to avoid data inconsistency or expiration issues.

Basic usage example:

@Cacheable(value = "clz" ,key = "'cid'+#cid")

 Explanation of properties within usage: 

  • value: used to specify the name of the cache. You can define different cache managers in the configuration file. The "value" here specifies the cache to be used.
  • key attribute: Use SpEL expression, "'cid'+#cid" to generate the cache key. This key will be generated dynamically from the value of the method's cid parameter. If different cid values ​​are passed in when the method is called, different cache keys will be generated, so different cid values ​​will correspond to different cache items. This allows you to store and retrieve cached data in different contexts.

2.2. @CachePut 

@CachePut is an annotation in the Spring Framework, used to store the return value of a method in the cache, usually used to update the data in the cache.

@CachePut method function:

  1. Update cache data:@CachePut is used to force the return value of a method to be stored in the cache, regardless of whether the same key already exists in the cache. This is useful for ensuring that the data in the cache is up to date, especially if the cached data needs to be updated manually.
  2. Dynamically generate cache keys:@CachePut allows you to use Spring Expression Language (SpEL) expressions to dynamically generate keys for cache items. This allows you to generate cache keys based on method parameters or other conditions to ensure that different cache items have different keys.
  3. Conditional update:@CachePut supports condition and unless attributes, which can control whether to perform cache update operations based on conditions. This allows you to manage your cache more flexibly by updating the cache only under specific conditions.
  4. Clear the specified cache entry:By configuring the allEntries attribute to true, you can clear all cache entries related to the specified cache instead of just updating a specific cache entry.
  5. Control update timing:Using the beforeInvocation attribute, you can control whether cache updates are triggered before the method is executed or after the method is executed successfully.

Note:

  • The @CachePut annotation is used to update data in the cache.Unlike @Cacheable, it will execute the method body and store the value returned by the method in the cache to ensure caching The data in is the latest.
  • If the data in the cache does not exist, @CachePut will create a new cache entry.

 Basic usage example:

@CachePut(value = "xx",key = "'cid:'+#cid")

Explanation of properties within usage: 

  • @CachePutAnnotations are used to store the return value of a method into the cache, and are usually used to update data in the cache.
  • is different from @Cacheable. It does not check whether the same key already exists in the cache. Instead, it directly stores the return value of the method into the cache to ensure that the data in the cache is up to date. of.
  • This is useful for updating cache items to ensure that the data in the cache is in sync with the backend data.

2.3. @CacheEvict

@CacheEvict is an annotation in Spring Framework, used to remove specified cache items from the cache or clear the entire cache.

@CacheEvict method function:

 

  1. Clear specified cache items:You can use @CacheEvict to clear cache items in one or more specific caches to ensure that the data in the cache remains up to date or when certain conditions are met. clear cache.
  2. Conditional clearing:@CacheEvict supports condition and unless attributes, which can control whether to perform cache clearing operations based on conditions. This allows you to manage your cache more flexibly by only clearing the cache when certain conditions are met.
  3. Clear the entire cache:By setting the allEntries property to true, you can clear the entire cache, rather than just clearing specific cache entries. This is useful for scenarios where the cache needs to be cleared globally under certain circumstances.
  4. Control clearing timing:Using the beforeInvocation attribute, you can control whether the cache clearing operation is triggered before the method is executed or after the method is executed successfully.
  5. Clear multiple entries from the cache:You can set a cache key expression via the key attribute to delete cache entries that match a specific key pattern. This allows you to delete cached items according to a certain pattern.

The main function of the @CacheEvict annotation is to remove specified cache items from the cache or clear the entire cache to ensure that the data in the cache remains up-to-date or to clear the cache based on conditions. It provides multiple properties that allow you to configure how and when to clear the cache as needed to meet specific business needs.

 Basic usage example:

@CacheEvict(value = "xx",key = "'cid:'+#cid",allEntries = true)

 Explanation of properties within usage:

  • value attribute: Set to "xx", indicating that the cache named "xx" is to be cleared. Typically, you need to define the corresponding cache manager in the configuration to ensure that it is associated with this cache name.
  • key attribute: Use the SpEL expression "'cid:'+#cid" to generate the key for the cache item. This key will be dynamically generated from the method's cid parameter value, prefixed with "cid:". This will cause cache entries matching "cid:" followed by the cid parameter value to be cleared.
  • allEntries attribute: Set to true to clear the entire cache. If allEntries is set to true, the key attribute is ignored and all cached entries in the specified cache are cleared. In this example, regardless of the value of the cid parameter, all contents of the cache named "xx" are cleared.

2.4. Summary

@Cacheable, @CachePut and @CacheEvict are annotations used to manage cache in Spring Framework. They have different functions and behaviors:

  • @Cacheable:
  1. Function:@Cacheable is used to declare that the return value of a method can be cached, that is, when the method is called, Spring will first check the cache, if the corresponding result exists in the cache , the cached value will be returned without executing the method body.
  2. Main purpose:Improving performance and avoiding repeated execution of the same method, suitable for read operations, not used for updating data.
  3. Configuration:You can specify the cache name, cache key, conditions, etc.
  • @CachePut:
  1. Function:@CachePut is used to force the return value of the method to be stored in the cache, and is usually used to update the data in the cache.
  2. Main purpose:Update the cache and put the value returned by the method into the cache, suitable for write operations.
  3. Configuration:You can specify the cache name, cache key, conditions, etc.
  • @CacheEvict:
  1. Function:@CacheEvict is used to remove the specified cache item from the cache or clear the entire cache.
  2. Main purpose:Clear cache items, keep the data in the cache up to date or clear the cache based on conditions.
  3. Configuration:You can specify the cache name, cache key, conditions, whether to clear the entire cache, etc.

Summary of differences:

  • @Cacheable Used to cache the return value of a method to avoid repeated execution of the method and is suitable for read operations.
  • @CachePut Used to store the return value of the method into the cache, usually used to update the data in the cache, suitable for write operations.
  • @CacheEvict Used to clear cache items. You can clear specified cache items or the entire cache.

About use: 

These annotations can be used in combination according to specific business needs to implement flexible caching strategies. For example, you can use @Cacheable  to cache the results of read operations, use  to update cache items, use  to clear the data in the cache, to meet different caching needs.  @CachePut @CacheEvict

3. Redis’ breakdown and penetration avalanche

When it comes to Redis, "breakdown", "penetration", and "avalanche" are some common problems related to the high availability and stability of the cache system. Below I will explain these three questions in detail:

  • Cache Breakdown:

Appears when hotspot data is invalid. When a specific key expires and a large number of concurrent requests are received, these requests bypass the cache and directly access the database, causing a sudden increase in database pressure. This is because after the cache is invalidated, the data cannot be obtained from the cache during the next access, but must be obtained from the database.

  • Cache Penetration:

When a malicious user requests a key that does not exist in the cache or database, the cache system cannot serve the data and these requests go directly to the database. This can lead to increased database load or even a denial of service attack. In order to deal with the penetration problem, you can set a null value when the key does not exist in the query or use methods such as Bloom filters to filter invalid requests.

  • 雪崩(Cache Avalanche):

When a large number of keys in the cache become invalid at the same time, a large number of requests directly access the back-end database, causing a sudden increase in pressure on the database and even a collapse. This is usually due to the data in the cache being set to the same expiration time, causing a large number of keys to expire at the same time, causing an avalanche effect. In order to avoid avalanche problems, strategies such as random expiration time and adding preloading of hotspot data can be adopted.

To combat these issues, here are some solutions you can take:

  • For breakdown problems, you can use mutex locks or set a short expiration time to protect hot data and ensure that there is valid data in the cache.
  • For penetration problems, technologies such as Bloom filters can be used to filter invalid requests to ensure that the cache system only processes valid requests.
  • For avalanche problems, strategies such as distributed caching, multi-level caching, and cache preheating can be used to ensure even distribution of data in the cache and avoid the simultaneous failure of a large amount of data.

               Okay, that’s it for today! ! Hope this helps! !​ 

Guess you like

Origin blog.csdn.net/m0_74915426/article/details/134353702