要在Spring Boot中集成MyBatis Plus和Redis,首先需要添加相關的依賴。在pom.xml文件中添加以下依賴:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
接下來,在application.properties文件中配置Redis的連接信息:
spring.redis.host=127.0.0.1
spring.redis.port=6379
然后,創建一個RedisConfiguration類,用于配置RedisTemplate和RedisCacheManager:
@Configuration
public class RedisConfiguration {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(cacheConfiguration)
.build();
}
}
最后,在MyBatis Plus的配置類中開啟二級緩存,并設置Redis作為緩存:
@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return new MybatisPlusCustomizers();
}
static class MybatisPlusCustomizers implements ConfigurationCustomizer {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
configuration.setCacheEnabled(true);
configuration.addCache(new RedisCache("mybatis-plus", new JedisCache(redisTemplate)));
}
}
}
現在,MyBatis Plus和Redis已經集成成功。您可以在MyBatis的Mapper接口中使用@CacheNamespace注解來開啟二級緩存,并指定緩存的名稱:
@Mapper
@CacheNamespace(implementation = RedisCache.class, properties = {@Property(name = "cache.days", value = "1")})
public interface UserMapper extends BaseMapper<User> {
// your methods here
}
這樣就完成了MyBatis Plus和Redis的集成。您可以在項目中使用MyBatis Plus進行數據庫操作,并使用Redis作為緩存來提高性能。