访问数据库使用redis作为mysql的缓存(redis和mysql结合)

访问数据库使用redis作为mysql的缓存(redis和mysql结合)首先声明一下,我是在一个SSM项目的基础上进行优化的,所以就不进行基础的介绍了。下面我也补充一些知识点:redis:内存型数据库,有持久化功能,具备分布式特性,可靠性高,适用于对读写效率要求都很高,数据处理业务复杂和对安全性要求较高的系统(如新浪微博的计数和微博发布部分系统,对数据安全性、读写要求都很高)。缓存机制说明:所有的查询结果都放进了缓存,也就是把MySQL查询的结果放…

大家好,又见面了,我是你们的朋友全栈君。

首先声明一下,我是在一个SSM项目的基础上进行优化的,所以就不进行基础的介绍了。

下面我也补充一些知识点:

redis:

内存型数据库,有持久化功能,具备分布式特性,可靠性高,适用于对读写效率要求都很高,数据处理业务复杂和对安全性要求较高的系统(如新浪微博的计数和微博发布部分系统,对数据安全性、读写要求都很高)。

缓存机制说明:

所有的查询结果都放进了缓存,也就是把MySQL查询的结果放到了redis中去, 然后第二次发起该条查询时就可以从redis中去读取查询的结果,从而不与MySQL交互,从而达到优化的效果,redis的查询速度之于MySQL的查询速度相当于 内存读写速度 /硬盘读写速度。

reids的安装很简单,我会在文末附上文件地址,只需要解压缩,然后点击打开redis-server.exe即可

下面正式开始:

1.pom.xml文件添加如下:

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

    <!--导入MyBatis和redis的信息配置-->
   <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>
   <!-- 自动扫描 -->
   <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}" />
      <!-- 初始化连接大小 -->
      <property name="initialSize" value="${initialSize}"></property>
      <!-- 连接池最大数量 -->
      <property name="maxActive" value="${maxActive}"></property>
      <!-- 连接池最大空闲 -->
      <property name="maxIdle" value="${maxIdle}"></property>
      <!-- 连接池最小空闲 -->
      <property name="minIdle" value="${minIdle}"></property>
      <!-- 获取连接最大等待时间 -->
      <property name="maxWait" value="${maxWait}"></property>
      <!-- 空闲连接回收 -->
       <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>
       <!-- 每次取出连接是否进行测试,如果为true,影响性能 -->
       <property name="testOnBorrow" value="false"/>
       <!-- 测试连接执行的sql -->
      <property name="validationQuery" value="SELECT 1" />
      <!-- 空闲时是否进行验证,检查对象是否有效,默认为false -->
       <property name="testWhileIdle" value="true"/>
   </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自动扫描mapping.xml文件 -->  
        <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">
                  <!--使用下面的方式配置参数,一行配置一个 -->
                  <value>
                     helperDialect=postgresql
                     reasonable=true
                     supportMethodsArguments=true
                     params=count=countSql
                     autoRuntimeDialect=true
                  </value>
               </property>
            </bean>
         </array>
      </property>

   </bean>


  
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.hanpeng" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
   </bean>
   
   <!-- basedao使用 -->
   <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"
      scope="prototype">
      <constructor-arg index="0" ref="sqlSessionFactory" />
   </bean>

   <!-- (事务管理)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 -->
   <!-- 配置JedisPoolConfig实例 -->
   <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>

   <!-- 配置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>

   <!-- 配置RedisTemplate -->
   <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
      <property name="connectionFactory" ref="jedisConnectionFactory" />
   </bean>

   <!-- 配置RedisCacheManager -->
   <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
      <constructor-arg ref="redisTemplate" />
      <property name="defaultExpiration" value="${redis.expiration}" />
   </bean>

   <!-- 配置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.缓存主要在service层进行,查询的结果会缓存,把对象序列号存到redis中去,key就是注解中的参数,例如@Cacheable(“findUsers”): 存在redis中的key就是findUsers。缓存了这个结果之后再次请求这个方法就不会去数据库中查,而是从redis缓存中读取数据,这样就减少了跟数据库之间的交互。然后修改、删除、增加操作就会清除缓存,保持数据的一致性。

RedisCacheConfig: 需要增加这个配置类,会在applicationContex配置文件中注册这个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配置类(通过spring管理redis缓存配置)
 * @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();
    }

    /**
     * 带参数的构造方法 初始化所有的成员变量
     *
     * @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”)注解的意义就是把该方法的查询结果放到redis中去,下一次再发起查询就去redis中去取,存在redis中的数据的key就是a;
 * @CacheEvict(value={“a”,”b”},allEntries=true) 的意思就是执行该方法后要清除redis中key名称为a,b的数据;
 */
@Service(“userService”)
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)  
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper iUserDao;

    @Cacheable(“getUserById”) //标注该方法查询的结果进入缓存,再次访问时直接读取缓存中的数据
    @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)//清空缓存,allEntries变量表示所有对象的缓存都清除
    @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安装包获取地址 https://download.csdn.net/download/qq_33609401/10851061

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/149836.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • JavaScript之正则表达式的使用方法详细介绍[通俗易懂]

    JavaScript之正则表达式的使用方法详细介绍[通俗易懂]首先必须说明的是,这类文章(js正则表达式)在c站或者整个it类论坛是很多人写过的,而我认为我这篇的不同之处在于更加“小白”化,这也与我一贯的风格有关吧。关于JavaScript正则表达式,其他的文章大多一上来就太过激进,不利于初学者学习(我当粗就是这么被劝退的),这也是我为什么要坚持写这篇文章,希望小白在看了这篇文章后,不管能不能完全掌握JavaScript正则表达式,但至少对JavaScript正则表达式能有一个比较深刻的印象吧。

    2025年8月5日
    6
  • Eclipse中SVN插件的基本使用「建议收藏」

    Eclipse中SVN插件的基本使用「建议收藏」首先在提交代码的时候,会看到有的文件前会有雪花标志,代表该文件被修改过。提交代码的时候,点击整个项目,右键—team—与资源库同步,这个目的是检查本地的代码和服务器上的代码有没有冲突,如果有冲突的话,应该像将冲突解决,否则提交代码会出错,解决冲突看我的另一篇博客。点击与资源库同步按钮之后,会跳转到TeamSynchronizing界面,这个时候eclipse会自动检测本…

    2022年9月26日
    4
  • XP中轻松获取未使用的IP地址「建议收藏」

    XP中轻松获取未使用的IP地址

    2022年3月11日
    45
  • LTE-FDD和TDD帧结构「建议收藏」

    LTE-FDD和TDD帧结构「建议收藏」1.两种双工模式LTE支持两种双工模式:TDD和FDD,于是LTE定义了两种帧结构:TDD帧结构和FDD帧结构。LTE标准制定之初就充分考虑了TDD和FDD双工方式在实现中的异同,增大两者共同点、减少两者差异点。两种帧结构设计的差别,会导致系统实现方面的不同,但主要的不同集中在物理层(PHY)的实现上,而在媒介接入控制层(MAC)、无线链路控制(RLC)层的差别不大,在更高层的设计上几乎没…

    2022年6月10日
    119
  • 采用CreateThread()创建多线程程序[通俗易懂]

    采用CreateThread()创建多线程程序[通俗易懂]采用CreateThread()创建多线程程序在window环境下,Win32提供了一系列的API函数来完成线程的创建、挂起、恢复、终结以及通信等工作:1、主要的函数列表:序号函数名功能1CreateThread()创建一个新线程2ExitThread()正

    2022年7月11日
    24
  • tar 打包压缩命令

    tar 打包压缩命令tar命令用于文件的打包或压缩,是最为常用的打包压缩命令,其语法格式如下:tar[选项]文件名.tar.gz源文件tar-cvfzxxx.tar.gzsource_file(tar-cvfz包名.tar.gz源文件)#以tar.gz方式打包并gz方式压缩tar-xvfzxxx.tar.gz-Cpath(tar-xvfzxxx.tar.gz-C目标路径)#解压缩包注意:使用tar命令,打包仅仅是打包xxx.tar,打包

    2022年5月31日
    84

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号