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

Introduction to the method of adding Redis support to SSM project

尚
forward
2019-12-21 17:45:202027browse

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);
        }
    }
}
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;

    }
}

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>

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>

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>

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"));
    }

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:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete