前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >访问数据库使用redis作为mysql的缓存(redis和mysql结合)

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

作者头像
全栈程序员站长
发布于 2022-07-05 08:33:04
发布于 2022-07-05 08:33:04
4.2K00
代码可运行
举报
运行总次数:0
代码可运行

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

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

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

redis

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

缓存机制说明:

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

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

下面正式开始:

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!--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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# 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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?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。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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.cn/149836.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
使用Spring Data Redis实现数据缓存
引言 目前很多系统为了解决数据读写的性能瓶颈,在系统架构设计中使用Redis实现缓存,Spring框架为了让开发人员更加方便快捷的使用Redis实现缓存,对Redis的操作进行了包装。 0.缓存 个人理解的缓存是指用于存储频繁使用的数据的空间,关注点是存储数据的空间和使用频繁的数据。缓存技术,简单的说就是先从缓存中查询数据是否存在,存在则直接返回,不存在再执行相应的操作获取数据,并将获取的数据存储到缓存中,它是一种提升系统性能的重要方法。 1.Redis Redis是一个开源的、内存存储key-value类
JavaQ
2018/04/04
9030
使用Spring Data Redis实现数据缓存
自定义注解设置缓存有效期的正确姿势
引言 redis缓存的有效期可以通过xml配置文件设置(默认有效期),也可以通过编码的方式手动去设置,但是这两种方式都存在缺陷。xml方式设置的是全局的默认有效期,虽然灵活,但不能给某个缓存设置单独的有效期;硬编码方式虽然可以给不同的缓存设置单独的有效期,但是管理上不够灵活。Spring提供的Cache相关注解中并没有提供有效期的配置参数,so,自定义注解实现缓存有效期的灵活设置诞生了。 Redis缓存 如何使用Redis实现数据缓存,请参考上篇《使用Spring-Data-Redis实现数据缓存》。 工具
JavaQ
2018/04/04
1.1K0
Spring启用缓存
Spring对缓存的支持类似于对事务的支持,Spring缓存的思想是在调用方法时,会把该方法的参数和返回结果作为一个键值对存放于缓存中,下次在调用该方法时直接从缓存返回结果。
Tim在路上
2020/08/04
6960
maven+springmvc+mybatis+redis 缓存查询实例,附有源码地址,使用redis注解和hash数据格式set,get两种方式讲解
文章很长,但大部分是代码,耐心看,要两三个小时。文章循序渐进,跟着走就行了。也可能会出现问题,网上百度一定能解决的。文章看完就能对redis怎么缓存数据有个清晰的认识了。
全栈程序员站长
2022/08/09
6510
maven+springmvc+mybatis+redis 缓存查询实例,附有源码地址,使用redis注解和hash数据格式set,get两种方式讲解
spring的缓存(cache)-分布式缓存
注:本文篇幅有点长,所以建议各位下载源码学习。(如需要请收藏!转载请声明来源,谢谢!)
逍遥壮士
2020/09/18
2.2K0
spring的缓存(cache)-分布式缓存
SpringCache与redis集成,优雅的缓存解决方案
缓存可以说是加速服务响应速度的一种非常有效并且简单的方式。在缓存领域,有很多知名的框架,如EhCache 、Guava、HazelCast等。
java思维导图
2020/08/24
8880
SpringCache与redis集成,优雅的缓存解决方案
Redis 缓存 + Spring 的集成示例 (不错的bolg)
http://blog.csdn.net/defonds/article/details/48716161  
bear_fish
2018/09/20
4630
Redis 缓存 + Spring 的集成示例  (不错的bolg)
Spring基于注解整合Redis
Redis是一种内存中的数据结构存储系统,被广泛用于缓存、消息队列等场景。Spring提供了对Redis的整合,使得在Spring应用中使用Redis变得更加方便和灵活。本文将介绍如何使用Spring注解来整合Redis。
大盘鸡拌面
2024/04/16
1910
spring整合spring-data-redis和spring-session-data-redis通过shiro实现单点登录
shiro_user_kickout和shiro_user_online,跟上面一样通过下面这个缓存管理器创建,通过他们实现单点登录或限定其他登录数.
全栈程序员站长
2022/08/18
1.1K0
2 Springboot中使用redis,配置redis的key value生成策略
上一篇里讲过了redis在spring boot中的简单使用,对于单个对象的增删改查的默认操作。
天涯泪小武
2019/01/17
4K2
springmvc+redis实现简单消息队列
有一只柴犬
2024/01/25
1430
SSM整合redis
在学习Redis的时候,大家应该知道,JAVA操作redis通常使用的是Jedis,通过java代码来操作redis的数据存储读取等操作,用过的人应该知道,Jedis客户端已经足够简单和轻量级了,但是呢,在此同时,Spring也为Redis提供了支持,就是在Spring-data模块中的Spring-Data-Redis(SDR),它一部分是基于Jedis客户端的API封装,另一部分是对Spring容器的整合。
全栈程序员站长
2022/08/12
6320
SSM整合redis
Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
环境建设:搭建Maven环境、Tomcat环境、需要MySql 数据库支持,使用的编程工具Eclipse (这些是前期准备);
yaohong
2019/09/11
7620
Spring全家桶之SpringData——SpringData Redis(附相关jar包)
SpringDataRedis是Spring大家族中的一个成员,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。
时间静止不是简史
2020/07/27
5460
Spring全家桶之SpringData——SpringData Redis(附相关jar包)
spring boot redis 数据库缓存用法
1.先从缓存中拿数据,如果有,直接返回。 2.如果拿到的为空,则数据库查询,然后将查询结果存到缓存中。 由此实现方式应该如下:
爱撸猫的杰
2019/05/08
9770
spring 整合 redis,以及spring的RedisTemplate如何使用
需要的jar包 spring-data-redis-1.6.2.RELEASE.jar jedis-2.7.2.jar(依赖 commons-pool2-2.3.jar) commons-pool2-2.3.jar
凯哥Java
2019/07/01
2K1
SpringMVC+redis整合
在网络上有一个很多人转载的springmvc+redis整合的案例,不过一直不完整,也是被各种人装来转去,现在基本将该框架搭建起来。
用户5640963
2019/07/26
4480
SpringMVC+redis整合
Spring 整合 Redis
这里配置就完成了。可以直接在service方法上面开启注解: 有4个注解@Cacheable,@CachePut , @CacheEvict,@CacheConfig @Cacheable、@CachePut、@CacheEvict 注释介绍 @Cacheable 作用和配置方法 @Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存 @Cacheable 主要的参数 value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个例如:这里和上面的name 的value对应,楼主这里写的是common @Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”} key 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合例如: @Cacheable(value=”testcache”,key=”#userName”) condition 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存例如: @Cacheable(value=”testcache”,condition=”#userName.length()>2”)
試毅-思伟
2018/09/06
5270
spring+redis的集成,redis做缓存
       Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。我们都知道,在日常的应用中,数据库瓶颈是最容易出现的。数据量太大和频繁的查询,由于磁盘IO性能的局限性,导致项目的性能越来越低。这时候,基于内存的缓存框架,就能解决我们很多问题。例如Memcache,Redis等。将一些频繁使用的数据放入缓存读取,大大降低了数据库的负担。提升了系统的性能。
别先生
2018/12/25
9840
Spring 框架:配置缓存管理器、注解参数与过期时间
SimpleCacheManager 是 Spring 提供的简单缓存管理器,用于管理内存缓存。适用于开发和测试阶段,或数据量小、缓存一致性要求不高的场景。
Yeats_Liao
2025/01/11
1250
Spring 框架:配置缓存管理器、注解参数与过期时间
推荐阅读
相关推荐
使用Spring Data Redis实现数据缓存
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验