当前位置:网站首页>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=true3.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=3000004..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
边栏推荐
- What are the changes in the 2022 PMP Exam?
- 从类生成XML架构
- Cmake tutorial step5 (add system self-test)
- Vulnerability recurrence - 48. Command injection in airflow DAG (cve-2020-11978)
- 读libco保存恢复现场汇编代码
- Seven Devops practices to improve application performance
- 职场进阶指南:大厂人必看书籍推荐
- Zabbix
- Server configuration jupyter environment
- Sentinel flow guard
猜你喜欢

To solve the problem of "double click PDF file, pop up", please install Evernote program

Sophon base 3.1 launched mlops function to provide wings for the operation of enterprise AI capabilities

Anaconda中配置PyTorch环境——win10系统(小白包会)

提高应用程序性能的7个DevOps实践

Thesis reading_ Medical NLP model_ EMBERT

Sophon AutoCV:助力AI工业化生产,实现视觉智能感知

Mask wearing detection based on yolov3

PMP认证需具备哪些条件啊?费用多少啊?

Vulnerability recurrence - 48. Command injection in airflow DAG (cve-2020-11978)

nacos -分布式事务-Seata** linux安装jdk ,mysql5.7启动nacos配置ideal 调用接口配合 (保姆级细节教程)
随机推荐
星环科技重磅推出数据要素流通平台Transwarp Navier,助力企业实现隐私保护下的数据安全流通与协作
GIMP 2.10教程「建议收藏」
最大人工岛[如何让一个连通分量的所有节点都记录总节点数?+给连通分量编号]
Easynmon Usage Summary
QT console printout
rsync
Sophon AutoCV:助力AI工业化生产,实现视觉智能感知
Which platform of outer disk gold is regular and safe, and how to distinguish it?
Teamcenter 消息注册前操作或後操作
Career advancement Guide: recommended books for people in big factories
Sophon CE社区版上线,免费Get轻量易用、高效智能的数据分析工具
证券网上开户安全吗?证券融资利率一般是多少?
提高应用程序性能的7个DevOps实践
请问下为啥有的表写sql能查到数据,但在数据地图里查不到啊,查表结构也搜不到
神经网络自我认知模型
论文阅读_医疗NLP模型_ EMBERT
Anaconda中配置PyTorch环境——win10系统(小白包会)
Redis Foundation
Customize the theme of matrix (I) night mode
ISPRS2022/雲檢測:Cloud detection with boundary nets基於邊界網的雲檢測