Table of Contents
Redis installation and use
SSM integrates Redis
Configure pom.xml to introduce Redis dependencies
redis.properties
applicationContext-redis.xml
MethodCacheInterceptor.java
RedisUtil.java tool class
Home Java javaTutorial Detailed explanation of SSM integration with Redis in Java

Detailed explanation of SSM integration with Redis in Java

Sep 30, 2017 am 10:31 AM
java redis Detailed explanation

Detailed explanation of SSM integration with Redis in Java

Redis installation and use

The first step is of course to install Redis. Here we take the installation on Windows as an example.

  • First download Redis, you can choose msi or zip package installation method

  • zip method needs to open the cmd window and run it in the decompressed directory redis-server redis.windows.confStart Redis

  • After installation in msi mode, Redis starts by default and does not require any configuration

  • You can modify the Redis port number, password and other configurations in the redis.windows.conf file. After the modification is completed, use the redis-server redis.windows.conf command to restart

  • Execute in the Redis installation directoryredis-cli -h 127.0.0.1 -p 6379 -a PasswordOpen the Redis operation interface

  • If an error (error) ERR operation not permitted is reported, use auth password for verification

SSM integrates Redis

Redis integration is carried out directly based on the framework integration of SSM in the previous article. It should be noted here that the pojo class stored in Redis must implement Serializableinterface .

Configure pom.xml to introduce Redis dependencies


1

2

3

4

5

6

7

<!--redis--><dependency>

    <groupId>org.springframework.data</groupId>

    <artifactId>spring-data-redis</artifactId>

    <version>1.6.1.RELEASE</version></dependency><dependency>

    <groupId>redis.clients</groupId>

    <artifactId>jedis</artifactId>

    <version>2.7.3</version></dependency>

Copy after login

redis.properties

1

2

3

4

5

6

7

8

redis.host=127.0.0.1

redis.port=6379

redis.password=redis

redis.maxIdle=100

redis.maxWait=1000

redis.testOnBorrow=true

redis.timeout=100000

defaultCacheExpireTime=3600

Copy after login

applicationContext-redis.xml


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

<?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:mvc="http://www.springframework.org/schema/mvc"      

xmlns:context="http://www.springframework.org/schema/context"      

xmlns:aop="http://www.springframework.org/schema/aop"      

xmlns:tx="http://www.springframework.org/schema/tx"      

xsi:schemaLocation="http://www.springframework.org/schema/beans       

http://www.springframework.org/schema/beans/spring-beans.xsd       

http://www.springframework.org/schema/mvc       

http://www.springframework.org/schema/mvc/spring-mvc.xsd       

http://www.springframework.org/schema/context       

http://www.springframework.org/schema/context/spring-context.xsd       

http://www.springframework.org/schema/aop       

http://www.springframework.org/schema/aop/spring-aop.xsd       

http://www.springframework.org/schema/tx       

http://www.springframework.org/schema/tx/spring-tx.xsd">

 

    <!--引入Redis配置文件-->

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

        <property name="locations">

            <list>

                <value>classpath:redis.properties</value>

            </list>

        </property>

    </bean>

 

    <!-- jedis 连接池配置 -->

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">

        <property name="maxIdle" value="${redis.maxIdle}"/>

        <property name="maxWaitMillis" value="${redis.maxWait}"/>

        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>

    </bean>

    <!-- redis连接工厂 -->

    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">

        <property name="poolConfig" ref="poolConfig"/>

        <property name="port" value="${redis.port}"/>

        <property name="hostName" value="${redis.host}"/>

        <property name="password" value="${redis.password}"/>

        <property name="timeout" value="${redis.timeout}"></property>

    </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.JdkSerializationRedisSerializer"/>

        </property>

    </bean>

    <!-- 缓存拦截器配置 -->

    <bean id="methodCacheInterceptor" class="com.zkh.interceptor.MethodCacheInterceptor">

        <property name="redisUtil" ref="redisUtil"/>

        <property name="defaultCacheExpireTime" value="${defaultCacheExpireTime}"/>

        <!-- 禁用缓存的类名列表 -->

        <property name="targetNamesList">

            <list>

                <value></value>

            </list>

        </property>

        <!-- 禁用缓存的方法名列表 -->

        <property name="methodNamesList">

            <list>

                <value></value>

            </list>

        </property>

    </bean>

    <bean id="redisUtil" class="com.zkh.util.RedisUtil">

        <property name="redisTemplate" ref="redisTemplate"/>

    </bean>

    <!--配置切面拦截方法 -->

    <aop:config proxy-target-class="true">

        <aop:pointcut id="controllerMethodPointcut" expression="       

        execution(* com.zkh.service.impl.*.select*(..))"/>

        <aop:advisor advice-ref="methodCacheInterceptor" pointcut-ref="controllerMethodPointcut"/>

    </aop:config></beans>

Copy after login

MethodCacheInterceptor.java


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

package com.zkh.interceptor;

import com.zkh.util.RedisUtil;

import org.aopalliance.intercept.MethodInterceptor;

import org.aopalliance.intercept.MethodInvocation;

import java.util.List;

/**

* Redis缓存过滤器

*/

public class MethodCacheInterceptor implements MethodInterceptor {   

private RedisUtil redisUtil;   

private List<String> targetNamesList; // 禁用缓存的类名列表

    private List<String> methodNamesList; // 禁用缓存的方法列表

    private String defaultCacheExpireTime; // 缓存默认的过期时间

 

    @Override

    public Object invoke(MethodInvocation invocation) throws Throwable {

        Object value = null;

 

        String targetName = invocation.getThis().getClass().getName();

        String methodName = invocation.getMethod().getName();       

        if (!isAddCache(targetName, methodName)) {           

        // 跳过缓存返回结果

            return invocation.proceed();

        }

        Object[] arguments = invocation.getArguments();

        String key = getCacheKey(targetName, methodName, arguments);       

        try {            // 判断是否有缓存

            if (redisUtil.exists(key)) {               

            return redisUtil.get(key);

            }            // 写入缓存

            value = invocation.proceed();           

            if (value != null) {               

            final String tkey = key;               

            final Object tvalue = value;               

            new Thread(new Runnable() {                   

            @Override

                    public void run() {

                        redisUtil.set(tkey, tvalue, Long.parseLong(defaultCacheExpireTime));

                    }

                }).start();

            }

        } catch (Exception e) {

            e.printStackTrace();           

            if (value == null) {               

            return invocation.proceed();

            }

        }        return value;

    }   

    /**    

    * 是否加入缓存    

    *    

    * @return    

    */

    private boolean isAddCache(String targetName, String methodName) {       

    boolean flag = true;       

    if (targetNamesList.contains(targetName)

                || methodNamesList.contains(methodName) || targetName.contains("$$EnhancerBySpringCGLIB$$")) {

            flag = false;

        }        return flag;

    }   

    /**    

     

    * 创建缓存key    

    *    

    * @param targetName    

     

   * @param methodName    

   * @param arguments   

    */

    private String getCacheKey(String targetName, String methodName,

                               Object[] arguments) {

        StringBuffer sbu = new StringBuffer();

        sbu.append(targetName).append("_").append(methodName);       

         

        if ((arguments != null) && (arguments.length != 0)) {          

         for (int i = 0; i < arguments.length; i++) {

                sbu.append("_").append(arguments[i]);

            }

        }        return sbu.toString();

    }    public void setRedisUtil(RedisUtil redisUtil) {       

    this.redisUtil = redisUtil;

    }    public void setTargetNamesList(List<String> targetNamesList) {       

    this.targetNamesList = targetNamesList;

    }    public void setMethodNamesList(List<String> methodNamesList) {       

    this.methodNamesList = methodNamesList;

    }    public void setDefaultCacheExpireTime(String defaultCacheExpireTime) {       

     

    this.defaultCacheExpireTime = defaultCacheExpireTime;

    }

}

Copy after login

RedisUtil.java tool class

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

package com.zkh.util;import org.apache.log4j.Logger;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;import java.io.Serializable;import java.util.Set;import java.util.concurrent.TimeUnit;/** * Redis工具类 */public class RedisUtil {    private RedisTemplate<Serializable, Object> redisTemplate;    /**     * 批量删除对应的value     *     * @param keys     */

    public void remove(final String... keys) {        for (String key : keys) {            remove(key);

        }

    }    /**     * 批量删除key     *     * @param pattern     */

    public void removePattern(final String pattern) {

        Set<Serializable> keys = redisTemplate.keys(pattern);        if (keys.size() > 0)

            redisTemplate.delete(keys);

    }    /**     * 删除对应的value     *     * @param key     */

    public void remove(final String key) {        if (exists(key)) {

            redisTemplate.delete(key);

        }

    }    /**     * 判断缓存中是否有对应的value     *     * @param key     * @return     */

    public boolean exists(final String key) {        return redisTemplate.hasKey(key);

    }    /**     * 读取缓存     *     * @param key     * @return     */

    public Object get(final String key) {

        Object result = null;

        ValueOperations<Serializable, Object> operations = redisTemplate

                .opsForValue();

        result = operations.get(key);        return result;

    }    /**     * 写入缓存     *     * @param key     * @param value     * @return     */

    public boolean set(final String key, Object value) {        boolean result = false;        try {

            ValueOperations<Serializable, Object> operations = redisTemplate

                    .opsForValue();

            operations.set(key, value);

            result = true;

        } catch (Exception e) {

            e.printStackTrace();

        }        return result;

    }    /**     * 写入缓存     *     * @param key     * @param value     * @return     */

    public boolean set(final String key, Object value, Long expireTime) {        boolean result = false;        try {

            ValueOperations<Serializable, Object> operations = redisTemplate

                    .opsForValue();

            operations.set(key, value);

            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);

            result = true;

        } catch (Exception e) {

            e.printStackTrace();

        }        return result;

    }    public void setRedisTemplate(

            RedisTemplate<Serializable, Object> redisTemplate) {        this.redisTemplate = redisTemplate;

    }

}

Copy after login


##Effect display

Detailed explanation of SSM integration with Redis in Java

There are no records in Redis at the beginning. Next, visit the first page of records.

Detailed explanation of SSM integration with Redis in Java

Check the cache again. The records have been stored in Redis, and the first visit will Reading data from Mysql

Detailed explanation of SSM integration with Redis in Java

Detailed explanation of SSM integration with Redis in Java

Press

F5 to refresh the page. You can see from the Tomcat console that there is no progress. SQL query, but reads cached data directly from Redis, reducing the burden on the database

Detailed explanation of SSM integration with Redis in Java

Detailed explanation of SSM integration with Redis in Java

The above is the detailed content of Detailed explanation of SSM integration with Redis in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

How to implement the underlying redis How to implement the underlying redis Apr 10, 2025 pm 07:21 PM

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

How to view all keys in redis How to view all keys in redis Apr 10, 2025 pm 07:15 PM

To view all keys in Redis, there are three ways: use the KEYS command to return all keys that match the specified pattern; use the SCAN command to iterate over the keys and return a set of keys; use the INFO command to get the total number of keys.

What to do if redis-server can't be found What to do if redis-server can't be found Apr 10, 2025 pm 06:54 PM

Steps to solve the problem that redis-server cannot find: Check the installation to make sure Redis is installed correctly; set the environment variables REDIS_HOST and REDIS_PORT; start the Redis server redis-server; check whether the server is running redis-cli ping.

How to use redis zset How to use redis zset Apr 10, 2025 pm 07:27 PM

Redis Ordered Sets (ZSets) are used to store ordered elements and sort by associated scores. The steps to use ZSet include: 1. Create a ZSet; 2. Add a member; 3. Get a member score; 4. Get a ranking; 5. Get a member in the ranking range; 6. Delete a member; 7. Get the number of elements; 8. Get the number of members in the score range.

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

H5: Tools, Frameworks, and Best Practices H5: Tools, Frameworks, and Best Practices Apr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

See all articles