Home Database Redis Introduction to the method of adding Redis support to SSM project

Introduction to the method of adding Redis support to SSM project

Dec 21, 2019 pm 05:45 PM
redis

Introduction to the method of adding Redis support to SSM project

You need to set up the SSM development environment and install Redis first. The following are the specific implementation steps:

1. Introduce the jedis framework package into the project: jedis- 2.8.2.jar, spring-data-redis-1.6.2.RELEASE.jar and commons-pool-1.6.jar. Pay attention to the introduced jar version. Too high or too low may cause exceptions. These versions are mentioned above. The combination is available for personal testing;

2. Two tool classes RedisUtil.java and SerializeUtil.java needed to write Redis

3. Add a new Cache class MybatisRedisCache to implement org.apache.ibatis .cache.Cache interface

4. Enable mybatis’ support for caching. In this project, modify the mybatis-config.xml file

5. Add customization to the relevant mapper.xml The cache class MybatisRedisCache

RedisUtil tool class is used to communicate with Redis data. SerializeUtil is a serialization tool class and is also a tool under the lang package. It is mainly used for serialization operations and also provides an object cloning interface. The following is the specific code:

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisUtil {
    private static String ADDR = "127.0.0.1";
    private static int PORT = 6379;
    private static int MAX_ACTIVE = 1024;

    private static int MAX_IDLE = 200;

    private static int MAX_WAIT = 100000;

    private static int TIMEOUT = 10000;

    private static boolean TEST_ON_BORROW = true;

    private static JedisPool jedisPool = null;

    static {
        try{
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
            jedisPool = new JedisPool(config,ADDR,PORT,TIMEOUT);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized static Jedis getJedis(){
        try{
            if(jedisPool != null){
                Jedis jedis = jedisPool.getResource();
                return jedis;
            }else{
                return null;
            }
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void returnResource(final Jedis jedis){
        if(jedis != null){
            jedisPool.returnResource(jedis);
        }
    }
}
Copy after login
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object unserialize(byte[] bytes) {
        if (bytes == null)
            return null;
        ByteArrayInputStream bais = null;
        try {
            // 反序列化
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MybatisRedisCache implements Cache {

    private static Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class); 

    /** The ReadWriteLock. */ 

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private String id;

    public MybatisRedisCache(final String id) {  

        if (id == null) {

            throw new IllegalArgumentException("Cache instances require an ID");

        }

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id="+id);

        this.id = id;

    }  
    public String getId() {

        return this.id;

    }
    public void putObject(Object key, Object value) {

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:"+key+"="+value);

        RedisUtil.getJedis().set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));

    }
    public Object getObject(Object key) {

        Object value = SerializeUtil.unserialize(RedisUtil.getJedis().get(SerializeUtil.serialize(key.toString())));

        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:"+key+"="+value);

        return value;
    }
    public Object removeObject(Object key) {

        return RedisUtil.getJedis().expire(SerializeUtil.serialize(key.toString()),0);

    }

 public void clear() {

        RedisUtil.getJedis().flushDB();

    }

   public int getSize() {

        return Integer.valueOf(RedisUtil.getJedis().dbSize().toString());

    }

   public ReadWriteLock getReadWriteLock() {

        return readWriteLock;

    }
}
Copy after login

mybatis-config.xml file, select global loading in the spring-mybatis.xml file:

<!-- 配置mybatis -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 加载mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:resource/mybatis-config.xml"></property>
        <!-- mapper扫描 -->
        <property name="mapperLocations" value="classpath:resource/mapper/*.xml"></property>
       </bean>
Copy after login

The following is the detailed code of mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"  
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
         <!-- 全局映射器启用缓存 -->
        <setting name="cacheEnabled" value="true"/>

        <!-- 查询时,关闭关联对象即时加载以提高性能 -->
        <setting name="lazyLoadingEnabled" value="false"/>

        <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
        <setting name="multipleResultSetsEnabled" value="true"/>

        <!-- 允许使用列标签代替列名 -->
        <setting name="useColumnLabel" value="true"/>

        <!-- 不允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
        <setting name="useGeneratedKeys" value="false"/>

        <!-- 给予被嵌套的resultMap以字段-属性的映射支持 FULL,PARTIAL -->
        <setting name="autoMappingBehavior" value="PARTIAL"/>

        <!-- 对于批量更新操作缓存SQL以提高性能 BATCH,SIMPLE -->
        <!-- <setting name="defaultExecutorType" value="BATCH" /> -->

        <!-- 数据库超过25000秒仍未响应则超时 -->
        <!-- <setting name="defaultStatementTimeout" value="25000" /> -->

        <!-- Allows using RowBounds on nested statements -->
        <setting name="safeRowBoundsEnabled" value="false"/>

        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn. -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>

        <!-- MyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default (SESSION) all queries executed during a session are cached. If localCacheScope=STATEMENT 
            local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession. -->
        <setting name="localCacheScope" value="SESSION"/>

        <!-- Specifies the JDBC type for null values when no specific JDBC type was provided for the parameter. Some drivers require specifying the column JDBC type but others work with generic values 
            like NULL, VARCHAR or OTHER. -->
        <setting name="jdbcTypeForNull" value="OTHER"/>

        <!-- Specifies which Object&#39;s methods trigger a lazy load -->
        <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
          <!-- 打印sql语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />  
</settings>

</configuration>
Copy after login

Finally, add the referenced

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.krk.sxytj.ytj2001.mapper.YTJ2001Mapper" >
  <cache type="com.krk.sxytj.utils.redis.MybatisRedisCache>
Copy after login

to the namespace of the mapping file mapper. You will find that the console prints out the SQL statement of the query just executed, and then performs the query with the same conditions. At this time, pay attention to the console. If no SQL is printed, the query results are directly output, indicating that the data is read from Redis and returned to you. It is not the result obtained by querying in the database. At this point the configuration is successful.

Of course, we can open the Redis client and server, find redis-cli in the Redis installation directory, double-click to open it, enter keys * and press Enter, you will see the generated key, and Redis will go to it based on the key. Get the required value.

During the actual operation, you should pay attention to the RedisUtil tool class. You need to set the port and ADDR according to your own situation. If the installed Redis has a password, you need to add AUTH. If there is no password set, this item is not required. When added to a tool class, even assigning a null value will not work.

I once tried this: private static String AUTH = " ";

As a result, this exception was reported when running: jedis.exceptions.JedisDataException: ERR Client sent AUTH, but no password is set

means that the redis server did not set a password, but the client sent an AUTH request to it. Additionally, classes to be cached need to implement Serializable. If you suspect that there is a problem with the Redis you installed, you can test it through the following method:

  @Test
    public void testRedis(){
         //连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        System.out.println("连接成功");
        //查看服务是否运行
        System.out.println("服务正在运行: "+jedis.ping());
        //设置 redis 字符串数据
        jedis.set("success", "oobom");
        // 获取存储的数据并输出
        System.out.println("redis 存储的字符串为: "+ jedis.get("success"));
    }
Copy after login

For more redis knowledge, please pay attention to the redis database tutorial column.

The above is the detailed content of Introduction to the method of adding Redis support to SSM project. 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 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

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

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).

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

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 read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

How to make message middleware for redis How to make message middleware for redis Apr 10, 2025 pm 07:51 PM

Redis, as a message middleware, supports production-consumption models, can persist messages and ensure reliable delivery. Using Redis as the message middleware enables low latency, reliable and scalable messaging.

See all articles