在SSM中使用redis作service层缓存和MyBatis二级缓存

redis 下载包括win32和win64 redis和可视化工具
https://download.csdn.net/download/grow_up_footstep/10749478
redis在windows端使用
下载压缩包后解压双击redis-server.exe或在目录下打开命令行窗口输入redis-server.exe redis.windows.conf运行redis
redis客户端分为自带的命令框和可视化工具
自带的命令框双击reids-cli.exe(没有设置密码的情况下)或在目录下打开命令行窗口输入redis-cli.exe -h localhost -p 6379运行redis客户端
可视化工具使用redisDesktopManager
一些redis简单的命令
查看密码 config get requirepass
设置密码config set requirepass “root” 这种方式设置后重启redis密码失效,永久的方式是去redis.window.conf文件中去找到requirepass修改,设置密码后启动客户端要加上-a root
设值 set key value
取值get key
查看所有键keys *
查看键数量dbsize
切换数据库select index
清空当前数据库flushdb
清空所有数据库fulushall

service层做缓存
pom文件中引入

<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.8.6.RELEASE</version>
    </dependency>

applicationContext.xml配置

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
              <property name="maxTotal" value="${redis.pool.maxTotal}"/>
              <property name="maxIdle" value="${redis.pool.maxIdle}"/>
              <property name="minIdle" value="${redis.pool.minIdle}"/>
              <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}"/>
              <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
              <property name="testOnReturn" value="${redis.pool.testOnReturn}"/>
              <property name="testWhileIdle" value="${redis.pool.testWhileIdle}"/>
              <property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"/>
       </bean>

       <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.password}"/>
              <property name="timeout" value="${redis.timeout}"/>
              <property name="poolConfig" ref="jedisPoolConfig"/>
              <!--使用连接池默认true-->
              <property name="usePool" value="true" />
       </bean>

       <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
              <property name="keySerializer">
                     <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
              </property>
              <property name="valueSerializer">
                     <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
              </property>
              <property name="hashKeySerializer">
                     <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
              </property>
              <property name="hashValueSerializer">
                     <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
              </property>
              <property name="connectionFactory" ref="jedisConnectionFactory"/>
       </bean>

       <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
              <constructor-arg index="0" ref="redisTemplate"/>
              <property name="defaultExpiration" value="${redis.cacheExpire}" />
       </bean>

       <!-- 启用缓存注解功能-->
       <cache:annotation-driven cache-manager="cacheManager" />

value直接去redis.properties中去取
redis.properties设置参照
https://yq.aliyun.com/articles/236383?spm=a2c4e.11153959.blogcont531067.14.64f445b52u5nWH
redisTemplate 参数设置
https://blog.csdn.net/whatlookingfor/article/details/51862969

service层

 //清空user下缓存
    //@CacheEvict(value = "user", allEntries = true)
    @Override
    public int insert(User user) {
        return userMapper.insert(user);
    }

    //@Cacheable(value = "user", key = "'selectByName('+#name+')'")
    @Override
    public User selectByName(String name) {
        return userMapper.selectByName(name);
    }

    //@Cacheable(value = "user", key = "'selectAll'")
    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

理解几个注释@CachePut不去检查缓存中是否存在,直接去数据库中取并放入缓存中
<cache:annotation-driven cache-manager=“cacheManager” />
mode属性可选值由proxy和aspectj,默认是proxy,当mode为proxy时,只有缓存方法在外部调用时Spring Cache
才会发生作用,并且只有Public方法上标注@Cacheable等标注才会起作用,当mode为aspectj时不存在上面两个问题
proxy-target-class属性表示是否代理class,默认是false,@Cacheable等可以标注在接口方法上,这对于基于
接口代理没有问题,当proxy-target-class为true或mode为aspectj时是基于class进行操作的,定义在接口上的注解不会识别的
参考https://www.cnblogs.com/fashflying/p/6908028.html

MyBatis二级缓存
applicationContext.xml文件中添加

<bean class="org.example.redis.MybatisRedisCacheTransfer">
           <property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
       </bean>

创建MybatisRedisCacheTransfer类和MybatisRedisCache
这些key保存在redis的list结构,以id作为list的key,每个mapper接口产生的id不变
参考https://www.jianshu.com/p/1d0be9bf3f80
Mapper.xml中添加

 <cache type="org.example.redis.MybatisRedisCache"/>
 
<!--#{name}自动加引号,预处理防止SQL注入 ${column}不加引号用于order by-->
  <select id="selectByName" resultType="User" useCache="true">
    select id, user_name, user_password, user_email, create_time
    from user
    where user_name=#{name}
  </select>
  
 <insert id="insert" flushCache="true">
    insert into user(user_name, user_password, user_email)
    value(#{userName}, #{userPassword}, #{userEmail})
  </insert>
  
  <select id="selectAll" resultMap="BaseResultMap" useCache="true">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select id, user_name, user_password, user_email, create_time
    from user
  </select>

Mybatis二级缓存useCache=true这个查询sql的结果进行缓存,其余insert update delete可以flushCache=true会把
redis中该mapper下的二级缓存清除
参照https://www.jianshu.com/p/52b0805f1950

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值