spring boot + mybatis plus 二级缓存配置方式

spring boot + mybatis plus 二级缓存配置方式

Spring boot

pom.xml 关键配置

	<!-- spring boot -->
	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.19.RELEASE</version>
        <relativePath/>
    </parent>
	<!-- mybatis plus -->
	<dependency>
	      <groupId>com.baomidou</groupId>
	      <artifactId>mybatis-plus-boot-starter</artifactId>
	      <version>2.3</version>
    </dependency>

关键代码

dao

	//使用注解方式开启二级缓存
	@CacheNamespace(implementation = MybatisCache.class)
	public interface TestDao extends BaseMapper<Test> {
		@Select("SELECT * from test,test2 where test.id = test2.f_id and test.id = #{id}")
		//不使用缓存
    	@Options(useCache = false)
    	Test getById(String id);

		//默认使用缓存
		@Select("select * from test where id = #{id}")
		Test getById(List<String> ids);
		
		int update(String id)
	}

mapper.xml

mapper 使用缓存的方式是使用”<cache-ref>“标签引用dao的命名空间,因为dao中已经开启缓存,
这样与dao中的缓存保持一直,如果mapper文件不引用缓存,
执行update方法时,不会清除dao的缓存,导致数据库数据与缓存数据不一致。
如果直接使用”<cache>“标签开启缓存,会与dao中的冲突,服务启动失败。

<mapper namespace="com.seentao.dmc.student.dao.StuClassTrainingDao">
	<!-- 缓存开启方式使用”<cache-ref>“标签引用dao中的缓存 -->
	<cache-ref namespace="com.seentao.dmc.student.dao.StuClassTrainingDao"/>
	<!-- 假设有些复杂的sql语句,dao中不支持,可在mapper文件中写 -->
	<update id="upldate" parameterType="java.util.List">
		update test
		set name = 'xxx'
		where id in
    	<foreach collection="list" index="index" item="item" open="(" close=")" separator=",">
        	#{item}
    	</foreach>
	</update>
</mapper>

工作中遇到的执行mapper文件中的SQL语句缓存没有清除的问题,在此记录一下,个人见解,如有错误请指正。

非常感谢您的提问。以下是 Spring Boot Mybatis Plus 使用 Redis 实现二级缓存的具体步骤和代码: 1. 首先,在 pom.xml 文件中添加 Redis 相关依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> ``` 2. 在 application.properties 文件中添加 Redis 相关配置: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.database=0 spring.redis.password= spring.redis.timeout=3000 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 ``` 3. 在 Mybatis Plus 的配置文件中开启二级缓存,并配置 Redis 缓存: ``` @Configuration @MapperScan("com.example.mapper") public class MybatisPlusConfig { @Bean public ConfigurationCustomizer configurationCustomizer() { return new ConfigurationCustomizer() { @Override public void customize(Configuration configuration) { // 开启二级缓存 configuration.setCacheEnabled(true); // 配置 Redis 缓存 RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(30)); // 设置缓存过期时间为 30 分钟 configuration.addCache(new RedisCache("mybatis-plus", new RedisCacheWriter() { @Override public void put(String key, byte[] value) { redisTemplate().opsForValue().set(key, value, Duration.ofMinutes(30)); } @Override public byte[] get(String key) { return redisTemplate().opsForValue().get(key); } @Override public void put(String key, byte[] value, long time, TimeUnit unit) { redisTemplate().opsForValue().set(key, value, Duration.ofMillis(unit.toMillis(time))); } @Override public void delete(String key) { redisTemplate().delete(key); } @Override public void clean() { redisTemplate().getConnectionFactory().getConnection().flushDb(); } @Override public long size() { return redisTemplate().getConnectionFactory().getConnection().dbSize(); } }, redisCacheConfiguration)); } }; } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory()); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer()); return redisTemplate; } @Bean public RedisConnectionFactory redisConnectionFactory() { LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(); lettuceConnectionFactory.setHostName("127.0.0.1"); lettuceConnectionFactory.setPort(6379); lettuceConnectionFactory.setPassword(""); lettuceConnectionFactory.setDatabase(0); return lettuceConnectionFactory; } } ``` 4. 在需要使用二级缓存的 Mapper 中添加 @CacheNamespace 注解: ``` @CacheNamespace(implementation = MybatisRedisCache.class, eviction = MybatisRedisCache.class) public interface UserMapper extends BaseMapper<User> { // ... } ``` 5. 最后,实现 MybatisRedisCache 类,继承自 RedisCache,重写 clear 方法: ``` public class MybatisRedisCache extends RedisCache { public MybatisRedisCache(String name, RedisCacheWriter cacheWriter, RedisCacheConfiguration configuration) { super(name, cacheWriter, configuration); } @Override public void clear() { RedisConnection connection = Objects.requireNonNull(getRedisCacheWriter().getRedisConnectionFactory().getConnection()); connection.flushDb(); connection.close(); } } ``` 以上就是 Spring Boot Mybatis Plus 使用 Redis 实现二级缓存的具体步骤和代码。希望能对您有所帮助!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值