当前位置:网站首页>Access the database and use redis as the cache of MySQL (a combination of redis and MySQL)
Access the database and use redis as the cache of MySQL (a combination of redis and MySQL)
2022-07-05 18:00:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
First of all, let's make a statement , I am in a SSM Optimized on the basis of the project , So I won't make a basic introduction .
Let me also add some knowledge points :
redis:
Memory type data library , It has persistence function , Distributed , High reliability , Apply to Reading and writing efficiency requirements are very high , Data processing Complex business and high security requirements The system of ( Such as Sina Weibo counting and Weibo publishing system , For data security 、 Reading and writing requirements are very high ).
Cache mechanism description :
All the query results are put into the cache , That is the MySQL The results of the query are put in redis In the middle , Then you can start this query for the second time from redis To read the results of the query , Thus not with MySQL Interaction , So as to achieve the effect of optimization ,redis The query speed of MySQL The query speed of is equivalent to Memory read and write speed / Hard disk read / write speed .
reids It's easy to install , I will attach the document address at the end of the text , Just unzip , Then click Open redis-server.exe that will do
Let's start :
1.pom.xml The file is added as follows :
<!--redis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
2.redis.properties
# Redis settings
redis.host=127.0.0.1
redis.port=6379
#redis.pass=password
redis.dbIndex=0
redis.expiration=3000
redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true
3.database.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username=###
password=###
#\u5b9a\u4e49\u521d\u59cb\u8fde\u63a5\u6570
initialSize=10
#\u5b9a\u4e49\u6700\u5927\u8fde\u63a5\u6570
maxActive=20
#\u5b9a\u4e49\u6700\u5927\u7a7a\u95f2
maxIdle=20
#\u5b9a\u4e49\u6700\u5c0f\u7a7a\u95f2
minIdle=1
#\u5b9a\u4e49\u6700\u957f\u7b49\u5f85\u65f6\u95f4
maxWait=60000
timeBetweenEvictionRunsMillis=300000
4..spring-mybatis.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.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">
<!-- Import MyBatis and redis Information configuration -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:database.properties</value>
<value>classpath:redis.properties</value>
</list>
</property>
</bean>
<!-- Automatic scanning -->
<context:component-scan base-package="com.hanpeng" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- Initialize connection size -->
<property name="initialSize" value="${initialSize}"></property>
<!-- Maximum number of connection pools -->
<property name="maxActive" value="${maxActive}"></property>
<!-- Connection pool maximum idle -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- Connection pool minimum idle -->
<property name="minIdle" value="${minIdle}"></property>
<!-- Get connection maximum wait time -->
<property name="maxWait" value="${maxWait}"></property>
<!-- Idle connection recovery -->
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>
<!-- Whether the connection is tested every time it is taken out , If true, Affect performance -->
<property name="testOnBorrow" value="false"/>
<!-- Test connection execution sql -->
<property name="validationQuery" value="SELECT 1" />
<!-- Whether to verify when idle , Check whether the object is valid , The default is false -->
<property name="testWhileIdle" value="true"/>
</bean>
<!-- spring and MyBatis Perfect integration , Unwanted mybatis Configuration map file -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- Automatic scanning mapping.xml file -->
<property name="mapperLocations" value="classpath*:mapping/**/*.xml"></property>
<property name="configLocation" value="mybatis-config.xml"></property>
<!--pageHelper-->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!-- Use the following method to configure parameters , Configure one... Line by line -->
<value>
helperDialect=postgresql
reasonable=true
supportMethodsArguments=true
params=count=countSql
autoRuntimeDialect=true
</value>
</property>
</bean>
</array>
</property>
</bean>
<!-- DAO Package name of the interface ,Spring Will automatically find the class under it -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.hanpeng" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- basedao Use -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"
scope="prototype">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<!-- ( Business management )transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- set leval -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true" />
<tx:method name="list*" read-only="true" />
<tx:method name="query*" read-only="true" />
<tx:method name="search*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="check*" read-only="true" />
<tx:method name="newLog*" propagation="NOT_SUPPORTED" />
<!-- other methods use the default transaction settings -->
<tx:method name="*" rollback-for="Exception" /> <!-- all exception rollback -->
</tx:attributes>
</tx:advice>
<!-- transaction config related... end -->
<!-- redis config start -->
<!-- To configure JedisPoolConfig example -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- To configure JedisConnectionFactory -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<!-- <property name="password" value="${redis.pass}" /> -->
<property name="database" value="${redis.dbIndex}" />
<property name="poolConfig" ref="poolConfig" />
</bean>
<!-- To configure RedisTemplate -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
<!-- To configure RedisCacheManager -->
<bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg ref="redisTemplate" />
<property name="defaultExpiration" value="${redis.expiration}" />
</bean>
<!-- To configure RedisCacheConfig -->
<bean id="redisCacheConfig" class="com.jd.service.RedisCacheConfig">
<constructor-arg ref="jedisConnectionFactory" />
<constructor-arg ref="redisTemplate" />
<constructor-arg ref="redisCacheManager" />
</bean>
<!-- redis config end -->
</beans>
5. Cache mainly in service Layer for , The results of the query will be cached , Save the object serial number to redis In the middle ,key That's the argument in the annotation , for example @Cacheable(“findUsers”): There is redis Medium key Namely findUsers. After caching the result, requesting this method again will not go to the database , But from redis Read data from the cache , This reduces the interaction with the database . And then modify 、 Delete 、 Increasing the operation will clear the cache , Keep data consistent .
RedisCacheConfig: You need to add this configuration class , Will be in applicationContex Register this in the configuration file bean.
package com.jd.service;
import java.lang.reflect.Method;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
/**
* @program: cloudConnectWMS
* @description: redis Configuration class ( adopt spring management redis Cache configuration )
* @author: by hanpeng
* @create: 2018-12-14 11:27
**/
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
private volatile JedisConnectionFactory jedisConnectionFactory;
private volatile RedisTemplate<String, String> redisTemplate;
private volatile RedisCacheManager redisCacheManager;
public RedisCacheConfig() {
super();
}
/**
* Construction method with parameters Initialize all member variables
*
* @param jedisConnectionFactory
* @param redisTemplate
* @param redisCacheManager
*/
public RedisCacheConfig(JedisConnectionFactory jedisConnectionFactory, RedisTemplate<String, String> redisTemplate,
RedisCacheManager redisCacheManager) {
this.jedisConnectionFactory = jedisConnectionFactory;
this.redisTemplate = redisTemplate;
this.redisCacheManager = redisCacheManager;
}
public JedisConnectionFactory getJedisConnecionFactory() {
return jedisConnectionFactory;
}
public RedisTemplate<String, String> getRedisTemplate() {
return redisTemplate;
}
public RedisCacheManager getRedisCacheManager() {
return redisCacheManager;
}
@Bean
public KeyGenerator customKeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... objects) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : objects) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
}
6.UserServiceImpl
import java.util.List; import javax.annotation.Resource; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional;
/** * userService * * @Cacheable(“a”) The meaning of annotation is to put the query results of this method into redis In the middle , The next time you start a query, go redis To get in , There is redis Of the data in key Namely a; * @CacheEvict(value={“a”,”b”},allEntries=true) It means to clear after executing this method redis in key The name is a,b The data of ; */ @Service(“userService”) @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) public class UserServiceImpl implements IUserService {
@Resource private UserMapper iUserDao;
@Cacheable(“getUserById”) // Mark the result of this method query into the cache , Directly read the data in the cache when accessing again @Override public User getUserById(int userId) { return this.iUserDao.selectByPrimaryKey(userId); }
@Cacheable(“getAllUser”) @Override public List<User> getAllUser() { return this.iUserDao.selectAllUser(); }
@CacheEvict(value= {“getAllUser”,”getUserById”,”findUsers”},allEntries=true)// Empty cache ,allEntries Variable indicates that the cache of all objects is cleared @Override public void insertUser(User user) { this.iUserDao.insertUser(user); }
@CacheEvict(value= {“getAllUser”,”getUserById”,”findUsers”},allEntries=true) @Override public void deleteUser(int id) { this.iUserDao.deleteUser(id); }
@Cacheable(“findUsers”) @Override public List<User> findUsers(String keyWords) { return iUserDao.findUsers(keyWords); }
@CacheEvict(value= {“getAllUser”,”getUserById”,”findUsers”},allEntries=true) @Override public void editUser(User user) { this.iUserDao.editUser(user); } }
redis Install the package to get the address https://download.csdn.net/download/qq_33609401/10851061
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/149836.html Link to the original text :https://javaforall.cn
边栏推荐
- GFS distributed file system
- 读libco保存恢复现场汇编代码
- 数据访问 - EntityFramework集成
- Career advancement Guide: recommended books for people in big factories
- matlab内建函数怎么不同颜色,matlab分段函数不同颜色绘图
- Cmake tutorial Step3 (requirements for adding libraries)
- Leetcode exercise - 206 Reverse linked list
- 从类生成XML架构
- Cmake tutorial step5 (add system self-test)
- mybash
猜你喜欢
What are the requirements for PMP certification? How much is it?
Tencent music launched its new product "quyimai", which provides music commercial copyright authorization
Abnormal recovery of virtual machine Oracle -- Xi Fenfei
Sophon autocv: help AI industrial production and realize visual intelligent perception
"Xiaodeng in operation and maintenance" is a single sign on solution for cloud applications
Sophon KG升级3.1:打破数据间壁垒,解放企业生产力
LeetCode 练习——206. 反转链表
Seven Devops practices to improve application performance
leetcode每日一练:旋转数组
2022新版PMP考试有哪些变化?
随机推荐
求解为啥all(())是True, 而any(())是FALSE?
较文心损失一点点性能提升很多
Daily exercise: a series of dates
Star Ring Technology launched transwarp Navier, a data element circulation platform, to help enterprises achieve secure data circulation and collaboration under privacy protection
Sophon CE社区版上线,免费Get轻量易用、高效智能的数据分析工具
leetcode每日一练:旋转数组
Mask wearing detection based on yolov3
小白入门NAS—快速搭建私有云教程系列(一)[通俗易懂]
解读:如何应对物联网目前面临的安全问题?
Please tell me why some tables can find data by writing SQL, but they can't be found in the data map, and the table structure can't be found
Teamcenter 消息注册前操作或后操作
QT控制台打印输出
ITK Example
Data access - entityframework integration
Teamcenter 消息注册前操作或後操作
Why is all (()) true and any (()) false?
Sophon autocv: help AI industrial production and realize visual intelligent perception
数值计算方法 Chapter8. 常微分方程的数值解
Action avant ou après l'enregistrement du message teamcenter
rsync