温馨提示×

springboot mybatisplus怎样与redis集成

小樊
103
2024-07-25 22:31:15
栏目: 云计算

要在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作为缓存来提高性能。

0