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'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!

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools