spring boot 集成 mybatis 使用redis做二级缓存

1引入(mybatis和redis)

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
           <groupId>io.lettuce</groupId>
           <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

2.给redis服务器设置密码和端口

在redis目录下,打开redis.windows.conf,在配置文件中有个参数:requirepass  这个就是配置redis访问密码的参数,去掉#

比如 requirepass 123qweasd

然后新建一个start.txt,输入redis-server.exe redis.windows.conf,指向配置文件,然后改成start.bat,打开服务端后,再打开

redis-cli.exe,就需要输入密码了,比如auth 123qweasd

端口同理

3.配置属性文件

mybatis.mapper-locations=classpath:/mapperxml/*Mapper.xml
mybatis.type-aliases-package=com.mapper
#使全局的映射器启用或禁用缓存。(开启二级缓存)
mybatis.configuration.cache-enabled=true
#全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。
mybatis.configuration.lazy-loading-enabled=true
#用来显示sql语句
logging.level.com.mapper=debug

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=123qweasd
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000

#如果由底层的缓存管理器支持创建,以逗号分隔的列表来缓存名称
spring.cache.cache-names=redisCache
#是否允许redis缓存空值
spring.cache.redis.cache-null-values=true
#redis的键前缀
spring.cache.redis.key-prefix=redisCache_
#缓存超时时间戳,设置为0不设置超时时间
spring.cache.redis.time-to-live=600000ms
#是否启用redis的键前缀
spring.cache.redis.use-key-prefix=true
#缓存类型,在默认的情况下,redis会根据上下文自动探测
spring.cache.type=redis

4.集成mybatis使用MybatisCodeHelper插件https://mp.csdn.net/postedit/85013465

5.使用注解@EnableCaching

@SpringBootApplication
@EnableCaching
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

5.在实现类的方法上使用@Cache注解,有三种,具体看http://www.cnblogs.com/junzi2099/p/8301796.html#_label2

(1)CachePut,表示将结果返回存放到缓存中,key可以定义为#result.id,可以定义条件condition

@Override
@CachePut(value="ccc",key = "'eee_'+#result.id",condition="#result!=null")
public User eee(Integer id) {
   return userMapper.selectByPrimaryKey(id);
}

(2)Cacheable,表示先从缓存中通过定义的键查询,找到就直接返回,找不到执行该方法,并将结果写入缓存,所以key不能定义为#result,只能定义为#id之类的参数,可以定义条件condition

@Override
@Cacheable(value="redisCache",key="'bbb_'+#minId+'_'+#maxId")
public List<User> bbb(Integer minId, Integer maxId) {
    PageHelper.startPage(2,3,"Id asc,Name desc");
    List<User> list1 = userMapper.findByIdGreaterThanEqualAndIdLessThanEqual(minId,maxId);
    return list1;
}

(3)CacheEvict通过定义的键移除缓存,allEntries删除全部,也可以用key删除指定

@Override
@CacheEvict(value="redisCache",allEntries = true)
public void delete(Integer id) {
    userMapper.deleteById(id);
}

那个value必须有值,但是好像没用,不管写啥都没区别

6.使用二级缓存很容易读到脏数据,可以设置缓存失效时间比如10分钟,对于一些准确性要求不高的数据,10分钟的延迟关系不大,但是对于更新,最好能直接从数据库读取数据,可以采用在实现类中用this.方法调用或直接自己写,自调用是不会启动事务和缓存的,另外对于命中率低的数据和返回结果集大的数据也不建议采用缓存

7.也可以自己完成redis的缓存,这样比较自由,例如可以设置不同的缓存失效时间,我自己想的一个办法,就是不管什么数据,先转成json,然后用redis的字符串存储保存,stringRedisTemplate是spring自动生成的bean,直接注入就可以了,expire用来设置超时时间

@Override
public User ddd(Integer id)  {
   String key="User_id_"+id;
   String s=stringRedisTemplate.opsForValue().get(key);
   User user;
   if (s!=null){
       user=JSON.parseObject(s,User.class);
       stringRedisTemplate.expire(key,10,TimeUnit.MINUTES);
       return user;
   }
   else {
       user=userMapper.selectByPrimaryKey(id);
       s=JSON.toJSONString(user);
       stringRedisTemplate.opsForValue().set(key,s);
       stringRedisTemplate.expire(key,10,TimeUnit.MINUTES);
       return user;
   }
}

猜你喜欢

转载自blog.csdn.net/weixin_43245707/article/details/85061834