mybatisplus自定义redis二级缓存管理器

时间: 2023-05-26 12:03:17 浏览: 25
MyBatis-Plus自带的Redis二级缓存默认使用了Jedis作为连接池,实现了比较简单的缓存管理,但是如果我们有自己定制的缓存管理器需求,可以通过继承`RedisCache`类并重写其中的方法来实现自定义的二级缓存管理器。 具体步骤如下: 1.继承`RedisCache`类并实现自己的缓存管理逻辑,例如: ```java public class MyRedisCache extends RedisCache { public MyRedisCache(String id) { super(id); } @Override public Object getObject(Object key) { // 自定义缓存读取逻辑 } @Override public void putObject(Object key, Object value) { // 自定义缓存写入逻辑 } @Override public Object removeObject(Object key) { // 自定义缓存删除逻辑 } //... 可以根据需要重写其他方法 } ``` 2.覆盖MyBatis-Plus自带的Redis二级缓存配置,将自定义的缓存管理器作为二级缓存实现,例如: ```java @Configuration public class MybatisPlusConfig { @Autowired private RedisConnectionFactory redisConnectionFactory; @Bean public RedisCacheManager redisCacheManager() { // 实现对指定缓存的自定义缓存管理器 RedisCacheWriter writer = RedisCacheWriter .nonLockingRedisCacheWriter(redisConnectionFactory); RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) .entryTtl(Duration.ofMinutes(10)); Map<String, RedisCacheConfiguration> caches = new HashMap<>(); caches.put("user", config); RedisCacheManager cacheManager = new RedisCacheManager(writer, config, caches); cacheManager.setTransactionAware(false); RedisCachePrefix cachePrefix = name -> "user:" + name + ":"; cacheManager.setCachePrefix(cachePrefix); // 设置自定义的缓存管理器 cacheManager.setCaches(Collections.singletonMap("user", new MyRedisCache("user"))); return cacheManager; } } ``` 通过上述配置可以发现,我们首先实现了一个自定义缓存管理器`MyRedisCache`,然后在`RedisCacheManager`中覆盖掉MyBatis-Plus自带的Redis二级缓存,将自定义的缓存管理器作为二级缓存实现。 最后在Mapper接口中启用二级缓存即可,例如: ```java @CacheNamespace(implementation = MybatisRedisCache.class, eviction = MybatisRedisCache.class) public interface UserMapper extends BaseMapper<User> { //... } ``` 需要注意的是,在覆盖MyBatis-Plus自带的Redis二级缓存时,要确保缓存名称和之前在MyBatis配置文件中定义的缓存名称一致,否则设置无效。

相关推荐

MyBatis-Plus 支持内置的 Redis 作为二级缓存,但是可能会遇到一些不可避免的性能问题,例如大量查询时的 Redis 连接池瓶颈,Redis key 命名空间冲突等。 因此,我们可以采用自定义 Redis 缓存管理器来替代默认的 RedisCacheManager,自定义缓存管理器需要实现 org.apache.ibatis.cache.Cache 接口。 以下是自定义 Redis 缓存管理器的示例代码: java public class CustomRedisCache implements Cache { private final String id; // 缓存实例名称 private final RedisTemplate<String, Object> redisTemplate; // RedisTemplate 实例 private static final long EXPIRE_TIME_IN_SECONDS = 3600; // 缓存过期时间,单位:秒 public CustomRedisCache(String id, RedisTemplate<String, Object> redisTemplate) { if (id == null || redisTemplate == null) { throw new IllegalArgumentException("缓存实例名称和 RedisTemplate 实例均不能为空!"); } this.id = id; this.redisTemplate = redisTemplate; } @Override public String getId() { return this.id; } @Override public void putObject(Object key, Object value) { if (key == null) { return; } redisTemplate.opsForValue().set(key.toString(), value, EXPIRE_TIME_IN_SECONDS, TimeUnit.SECONDS); } @Override public Object getObject(Object key) { return key == null ? null : redisTemplate.opsForValue().get(key.toString()); } @Override public Object removeObject(Object key) { if (key == null) { return null; } redisTemplate.delete(key.toString()); return null; } @Override public void clear() { Set<String> keys = redisTemplate.keys("*" + getId() + "*"); if (keys != null && keys.size() > 0) { redisTemplate.delete(keys); } } @Override public int getSize() { return redisTemplate.keys("*" + getId() + "*").size(); } @Override public ReadWriteLock getReadWriteLock() { return null; } } 接下来,我们需要将自定义 Redis 缓存管理器注册到 MyBatis 中,示例代码如下: java @Configuration public class MybatisConfig { @Autowired private RedisTemplate<String, Object> redisTemplate; @Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean(); sqlSessionFactory.setDataSource(dataSource); sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml")); sqlSessionFactory.setPlugins(new Interceptor[]{new PaginationInterceptor()}); sqlSessionFactory.setCache(new CustomRedisCache("mybatis_cache", redisTemplate)); // 注册自定义缓存管理器 return sqlSessionFactory; } } 最后,我们还需要在 MyBatis-Plus 的配置文件 mybatis-plus.yml 中添加一条配置,将 MyBatis 的缓存管理器设置为自定义的缓存管理器: yml mybatis-plus: configuration: cache-enabled: true # 允许缓存 # 使用自定义 Redis 缓存管理器 local-cache: # 是否使用一级缓存,默认为 true enabled: true # 默认缓存过期时间,单位:毫秒,默认值为 -1,即永不过期 ttl: -1 # 一级缓存最大数量,默认值为 1024 size: 1024 second-cache: # 是否使用二级缓存,默认为 true enabled: true # 默认缓存过期时间,单位:毫秒,默认值为 -1,即永不过期 ttl: -1 # 内置二级缓存管理器,支持Redis、Ehcache、Caffeine、H2、LevelDB、J2Cache等 cache-manager: com.baomidou.mybatisplus.extension.caches.RedisCacheManager # 自定义二级缓存管理器,必须实现 org.apache.ibatis.cache.Cache 接口 custom-cache: com.example.CustomRedisCache 参考链接: - https://mp.weixin.qq.com/s/GvF8ffYQbeytE0glCNV9Xg
MyBatis Plus提供了默认的Redis缓存管理器,但是有时候我们需要根据自己的业务需求来定制一个适合自己的缓存管理器,这里简单介绍一下如何自定义Redis缓存管理器: 1. 实现Cache接口 首先需要实现MyBatis的Cache接口,该接口定义了缓存操作的基本接口方法。可以参考默认的RedisCache实现。 public interface Cache { String getId(); void putObject(Object key, Object value); Object getObject(Object key); Object removeObject(Object key); void clear(); int getSize(); default void putObject(Object key, Object value, long ttl) { throw new UnsupportedOperationException("not support"); } } 2. 实现CacheManager接口 接着需要实现MyBatis的CacheManager接口,该接口负责管理各个缓存实例的生命周期以及提供创建缓存的方法。可以参考默认的RedisCacheManager实现。 public interface CacheManager { Cache getCache(String var1); void addCache(String var1); Set<String> getCacheNames(); default void destroy() { } } 3. 配置缓存管理器 在MyBatis的配置文件中配置自定义的缓存管理器和缓存实现类。可以像下面这样配置: <cache type="com.example.MyCacheManager"> </cache> 其中type属性值为自定义的CacheManager实现类。 4. 使用缓存 在Mapper接口方法上使用@CacheNamespace注解开启缓存功能并指定缓存管理器,例如: @Mapper @CacheNamespace(implementation = MyCacheManager.class) public interface UserMapper { @Select("select * from user where id = #{id}") @Options(useCache = true, flushCache = Options.FlushCachePolicy.FALSE) User selectById(@Param("id") int id); } 这样就可以在查询User对象时自动使用自定义的Redis缓存管理器进行缓存。
MybatisPlus已经提供了redis二级缓存的实现,只需要在配置文件中开启对应选项即可。如果需要自定义redis二级缓存的实现,可以通过实现Cache接口来实现。 1. 定义缓存类 java public class RedisCache implements Cache { private RedisTemplate<Object, Object> redisTemplate; private String cacheName; private final String CACHE_PREFIX = "mybatis_cache:"; public RedisCache(String cacheName) { this.cacheName = cacheName; } @Override public String getId() { return CACHE_PREFIX + cacheName; } @Override public void putObject(Object key, Object value) { redisTemplate.opsForHash().put(getId(), key, value); } @Override public Object getObject(Object key) { return redisTemplate.opsForHash().get(getId(), key); } @Override public Object removeObject(Object key) { return redisTemplate.opsForHash().delete(getId(), key); } @Override public void clear() { redisTemplate.delete(getId()); } @Override public int getSize() { return Math.toIntExact(redisTemplate.opsForHash().size(getId())); } @Override public ReadWriteLock getReadWriteLock() { return null; } public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) { this.redisTemplate = redisTemplate; } } 2. 配置RedisTemplate java @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setDefaultSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); redisTemplate.afterPropertiesSet(); return redisTemplate; } 3. 配置RedisCacheManager java @Bean public RedisCacheManager redisCacheManager(RedisTemplate<Object, Object> redisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager(new RedisCacheWriter() { @Override public void put(String name, byte[] key, byte[] value, Duration ttl) { redisTemplate.opsForHash().put(name, key, value); } @Override public byte[] get(String name, byte[] key) { return redisTemplate.opsForHash().get(name, key); } @Override public byte[] putIfAbsent(String name, byte[] key, byte[] value, Duration ttl) { byte[] currentValue = get(name, key); if (currentValue == null) { put(name, key, value, ttl); return null; } else { return currentValue; } } @Override public void remove(String name, byte[] key) { redisTemplate.opsForHash().delete(name, key); } @Override public void clean(String name, byte[] pattern) { Set<Object> keys = redisTemplate.opsForHash().keys(name); if (!CollectionUtils.isEmpty(keys)) { for (Object key : keys) { byte[] keyBytes = (byte[]) key; if (WildcardMatcher.match(new String(pattern), new String(keyBytes))) { remove(name, keyBytes); } } } } @Override public void clear(String name) { redisTemplate.delete(name); } @Override public void close() { // do nothing } },redisTemplate); return cacheManager; } 4. 配置缓存设置 java @MapperScan(value = "com.example.mapper", annotationClass = MyBatisPlusRedisCache.class) @Configuration public class RedisCacheConfig extends MybatisPlusPropertiesCustomizer { private final RedisTemplate<Object, Object> redisTemplate; private final RedisCacheManager redisCacheManager; public RedisCacheConfig(RedisTemplate<Object, Object> redisTemplate, RedisCacheManager redisCacheManager) { super(); this.redisTemplate = redisTemplate; this.redisCacheManager = redisCacheManager; } @Override public void customize(MybatisPlusProperties properties) { // 开启redis缓存 properties.getGlobalConfig().setCacheEnabled(true); properties.getGlobalConfig().setDefaultCache(new RedisCache(MpRedisCacheEnum.SECOND_CACHE_MODE.getCacheName())); // 自定义redis缓存 Map<String, Cache> cacheMap = new HashMap<>(); cacheMap.put(MpRedisCacheEnum.SECOND_CACHE_MODE.getCacheName(), new RedisCache(MpRedisCacheEnum.SECOND_CACHE_MODE.getCacheName())); redisCacheManager.setCaches(cacheMap); MybatisConfiguration configuration = properties.getConfiguration(); configuration.addInterceptor(new MybatisPlusRedisCacheInterceptor()); } } 5. 配置自定义拦截器 java public class MybatisPlusRedisCacheInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; Object parameter = invocation.getArgs()[1]; CacheKey cacheKey = mappedStatement.getCacheKey(parameter, mappedStatement.getConfiguration(), mappedStatement.getBoundSql(parameter)); BoundSql boundSql = mappedStatement.getBoundSql(parameter); Cache cache = mappedStatement.getCache(); if (cache instanceof RedisCache) { RedisCache redisCache = (RedisCache) cache; redisCache.setRedisTemplate(SpringUtil.getBean(RedisTemplate.class)); } return invocation.proceed(); } } 6. 定义注解标记需要采用自定义Redis缓存的方法 java @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface MyBatisPlusRedisCache { } 7. 在Mapper方法上添加注解 java @Mapper @MyBatisPlusRedisCache public interface UserMapper extends BaseMapper<User> { } 这样就完成了自定义Redis二级缓存的实现。注意,如果需要使用分布式锁来保证多线程下的缓存穿透问题,需要在putObject方法中添加分布式锁逻辑。
MyBatis-Plus 本身不支持二级缓存,但它可以与第三方缓存框架集成,比如 Redis。下面是如何使用 Redis 作为二级缓存的步骤: 1. 引入 Redis 依赖 在 pom.xml 文件中添加 Redis 相关依赖: xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.1.6.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-redis</artifactId> <version>2.1.1-SNAPSHOT</version> </dependency> 其中,spring-boot-starter-data-redis 是 SpringBoot 使用 Redis 的依赖,mybatis-redis 是 MyBatis-Plus 工具包支持 Redis 的依赖。 2. 配置 Redis 在 application.yml 文件中添加 Redis 配置: yaml spring: redis: host: localhost port: 6379 password: 3. 配置 Redis 缓存 在 MyBatis 的配置文件中配置 Redis 缓存: xml <cache type="org.mybatis.caches.redis.RedisCache"/> 4. 开启 Redis 二级缓存 在 MyBatis-Plus 的全局配置文件中,开启 Redis 二级缓存: java @Configuration public class MybatisPlusConfig { /** * 开启Mybatis-Plus二级缓存,需要配置RedisCache类 */ @Bean public ConfigurationCustomizer configurationCustomizer() { return configuration -> configuration.setCacheEnabled(true) .addCache(new RedisCache("mybatis-plus-redis-cache", true)); } } 其中,RedisCache 参数说明: - 第一个参数为缓存名称,可以自定义。 - 第二个参数为是否开启序列化,默认为 true。 至此,使用 Redis 作为二级缓存已经完成。在 MyBatis-Plus 的 CRUD 操作中,如果数据在 Redis 中存在,则直接从 Redis 中获取数据,否则从数据库中查询数据并缓存到 Redis 中。这样可以大大提高查询效率,减轻数据库负担。
MybatisPlus提供了自定义Redis缓存的功能,可以通过自定义Redis缓存实现数据的快速查询。 1. 引入Redis依赖 xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 2. 自定义缓存 java @Component public class RedisCache implements Cache { private final RedisTemplate<Object, Object> redisTemplate; private final String cacheName; private final long ttl; public RedisCache(RedisTemplate<Object, Object> redisTemplate, String cacheName) { this.redisTemplate = redisTemplate; this.cacheName = cacheName; this.ttl = 60 * 5; //默认5分钟过期时间 } public RedisCache(RedisTemplate<Object, Object> redisTemplate, String cacheName, long ttl) { this.redisTemplate = redisTemplate; this.cacheName = cacheName; this.ttl = ttl; } @Override public String getId() { return cacheName; } @Override public void putObject(Object key, Object value) { redisTemplate.opsForValue().set(key, value, ttl, TimeUnit.SECONDS); } @Override public Object getObject(Object key) { return redisTemplate.opsForValue().get(key); } @Override public Object removeObject(Object key) { redisTemplate.delete(key); return null; } @Override public void clear() { redisTemplate.delete(redisTemplate.keys("*" + cacheName + "*")); } @Override public int getSize() { return Math.toIntExact(redisTemplate.keys("*" + cacheName + "*").size()); } @Override public ReadWriteLock getReadWriteLock() { return null; } } 3. 注册自定义缓存 java @Configuration @EnableCaching public class CacheConfig extends CachingConfigurerSupport { private final RedisConnectionFactory redisConnectionFactory; public CacheConfig(RedisConnectionFactory redisConnectionFactory) { this.redisConnectionFactory = redisConnectionFactory; } @Bean public CacheManager cacheManager() { RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(10)) .disableCachingNullValues(); RedisCacheConfiguration userCacheConfig = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(5)) .disableCachingNullValues() .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<String, RedisCacheConfiguration>() {{ put("user", userCacheConfig); }}; RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(defaultCacheConfig) .withInitialCacheConfigurations(cacheConfigurations) .build(); return cacheManager; } @Bean @Override public CacheResolver cacheResolver() { return new SimpleCacheResolver(cacheManager()); } @Bean @Override public CacheErrorHandler errorHandler() { return new SimpleCacheErrorHandler(); } @Bean public Cache redisCache(RedisTemplate<Object, Object> redisTemplate) { return new RedisCache(redisTemplate, "product"); } } 4. 使用自定义缓存 在Mapper接口方法上添加@Cacheable注解,指定使用自定义的Redis缓存即可。 java @Mapper public interface UserMapper extends BaseMapper<User> { @Cacheable(value = "user", key = "#id") User getById(Long id); }
以下是一个使用MyBatis Plus和Redis作为二级缓存的示例代码: 1. 配置RedisTemplate java @Configuration public class RedisConfig { @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()); return redisTemplate; } } 2. 配置MyBatis Plus java @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(RedisTemplate<String, Object> redisTemplate) { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 分页插件 interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // Redis 二级缓存插件 RedisCache redisCache = new RedisCache(redisTemplate); Properties properties = new Properties(); properties.setProperty("redisCache.expire", "3600"); properties.setProperty("redisCache.cacheNullObject", "true"); RedisCacheInterceptor redisCacheInterceptor = new RedisCacheInterceptor(redisCache, properties); interceptor.addInnerInterceptor(redisCacheInterceptor); return interceptor; } @Bean public ConfigurationCustomizer configurationCustomizer(MybatisPlusInterceptor mybatisPlusInterceptor) { return configuration -> configuration.addInterceptor(mybatisPlusInterceptor); } } 3. 使用@CacheNamespace注解开启缓存 java @CacheNamespace(implementation = RedisCache.class, eviction = RedisCache.class) public interface UserMapper extends BaseMapper<User> { @Cacheable(value = "user:id", key = "#id") User getUserById(Long id); @CachePut(value = "user:id", key = "#user.id") int updateUserById(User user); @CacheEvict(value = "user:id", key = "#id") int deleteUserById(Long id); } 在这里,@CacheNamespace注解用于开启Redis缓存,并指定了缓存的实现类和清理策略。 @Cacheable注解用于查询缓存中的数据,@CachePut注解用于更新缓存中的数据,@CacheEvict注解用于删除缓存中的数据。 还可以在@Cacheable注解中指定缓存的名称和缓存的键值,以及在@CachePut和@CacheEvict注解中指定缓存的键值。 注意:在使用Redis作为二级缓存时,需要在mapper中使用@Cacheable注解进行数据的缓存和查询,同时要保证实体类的序列化和反序列化能够正确进行。
1. 引入依赖 在 pom.xml 文件中添加以下依赖: <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-extension</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>org.apache.ibatis</groupId> <artifactId>mybatis-redis-cache</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> 2. 配置 Redis 在 application.yml 配置文件中添加 Redis 的连接信息: spring: redis: host: 127.0.0.1 port: 6379 password: 123456 database: 0 pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: -1ms 3. 配置 MyBatis Plus 在 MyBatis Plus 配置文件中开启二级缓存并配置 Redis 缓存: mybatis-plus: configuration: cache-enabled: true # 开启二级缓存 local-cache-scope: session # 二级缓存作用域 lazy-loading-enabled: true # 开启懒加载 multiple-datasource-enabled: true # 开启多数据源 global-config: db-config: id-type: auto # 主键ID类型 field-strategy: not_empty # 字段非空验证 swagger2: true # 是否开启Swagger2 cache: enabled: true # 开启缓存 type: redis # 缓存类型 # 设置缓存前缀,默认是 mybatis:cache: # prefix: mybatisplus: spring: redis: cache: # 过期时间,默认1天 ttl: 86400 # 二级缓存前缀,默认是 mybatisplus:cache: key-prefix: mybatis-plus:cache: # 条目数量,默认256个 max-number-of-elements-in-cache: 256 4. 实体类开启缓存 在需要开启缓存的实体类上添加 @CacheNamespace 注解: @Data @NoArgsConstructor @TableName("student") @CacheNamespace(implementation = MybatisRedisCache.class, eviction = MybatisRedisCache.class, flushInterval = 60000) public class Student implements Serializable { @TableId(type = IdType.AUTO) private Long id; @TableField("name") private String name; @TableField("age") private Integer age; } 其中,implementation 和 eviction 属性的值均为 MybatisRedisCache.class,表示该实体类使用 Redis 缓存,并且缓存失效时间为 1 分钟(60 秒)。 5. 注册 Redis 缓存插件 在 Spring Boot 应用启动类中注册 Redis 缓存插件: @Configuration public class MyBatisPlusConfig { @Bean public RedisCachePlugin redisCachePlugin(RedisTemplate<Object, Object> redisTemplate) { return new RedisCachePlugin(redisTemplate); } } 6. 测试缓存 使用以下代码进行测试: @Test public void testRedisCache() { Student student1 = studentService.getById(1L); Student student2 = studentService.getById(1L); System.out.println("student1:" + student1); System.out.println("student2:" + student2); Assert.assertEquals(student1, student2); } 第一次查询会从数据库中获取数据并保存到 Redis 缓存,第二次查询会直接从 Redis 缓存中获取数据,输出结果如下: DEBUG [MybatisRedisCache] [Session XX] [Namespace com.example.demo.entity.Student] [Cache INSERT] Student(id=1, name=Tom, age=20) student1:Student(id=1, name=Tom, age=20) student2:Student(id=1, name=Tom, age=20)
Redis和Caffeine都是常用的缓存方案,而将它们结合起来使用,可以形成二级缓存方案。 二级缓存的核心思想是将数据存储在两个不同的缓存中,通常是一个内存缓存和一个持久化缓存,以提高缓存的效率和可靠性。在这种情况下,Caffeine可以用作内存缓存,而Redis可以用作持久化缓存。 使用Caffeine作为内存缓存可以提供非常快速的访问速度,并且数据可以在内存中保持最新状态。但是,Caffeine缓存是有限制的,如果缓存过多数据,可能导致内存使用过高,从而影响系统的性能。因此,我们需要一个持久化缓存来保存一些不常用的数据或者缓存数据的备份。 Redis是一个高效的键值存储系统,可以将数据保存在磁盘上,因此即使系统重启也不会丢失数据。Redis还提供了一些高级功能,如发布/订阅模式、事务和 Lua脚本执行。通过将Redis用作持久化缓存,我们可以使系统更可靠,并且可以存储更多的数据。 在实际应用中,我们可以使用Caffeine作为一级缓存,Redis作为二级缓存。当需要获取数据时,首先在Caffeine中查找,如果没有找到,则从Redis中获取,如果还没有找到,则从数据库中获取。在更新数据时,我们可以将数据先更新到数据库中,然后再更新到Caffeine和Redis中,以保持数据的一致性。 综上所述,结合Redis和Caffeine使用可以提高缓存的效率和可靠性,但是具体实现需要根据实际情况进行调整。
二级缓存是指在应用程序中同时使用两种不同的缓存技术,通常是将本地缓存和分布式缓存结合使用,以提高缓存的效率和可靠性。Guava和Redis都是常用的缓存库,下面介绍它们如何实现二级缓存。 1. Guava实现二级缓存 Guava是一个开源的Java工具库,其中包含了许多常用的工具类和数据结构,包括本地缓存。Guava本地缓存是指将数据存储在应用程序内存中的缓存,可以用于提高应用程序的性能和响应速度。但是,本地缓存的生命周期受到应用程序的生命周期限制,一旦应用程序结束,缓存中的数据也就不存在了。为了解决这个问题,我们可以将Guava本地缓存和分布式缓存结合使用,实现二级缓存。 具体实现方法如下: 1)创建Guava本地缓存 java LoadingCache<String, Object> localCache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(new CacheLoader<String, Object>() { @Override public Object load(String key) throws Exception { // 从数据库或其他数据源中加载数据 return loadDataFromDatabase(key); } }); 2)创建Redis分布式缓存 java JedisPool jedisPool = new JedisPool("localhost", 6379); Jedis jedis = jedisPool.getResource(); 3)在应用程序中使用二级缓存 java public Object getObject(String key) { Object value = null; try { // 先从本地缓存中获取数据 value = localCache.get(key); } catch (Exception e) { e.printStackTrace(); } if (value == null) { // 如果本地缓存中没有数据,则从Redis缓存中获取数据 byte[] bytes = jedis.get(key.getBytes()); if (bytes != null) { value = SerializationUtils.deserialize(bytes); // 将数据存储到本地缓存中 localCache.put(key, value); } } if (value == null) { // 如果Redis缓存中也没有数据,则从数据库或其他数据源中加载数据 value = loadDataFromDatabase(key); // 将数据存储到Redis缓存和本地缓存中 byte[] bytes = SerializationUtils.serialize(value); jedis.set(key.getBytes(), bytes); localCache.put(key, value); } return value; } 2. Redis实现二级缓存 Redis是一个开源的内存数据库,可以用于存储和管理缓存数据。Redis分布式缓存的优点是可以存储大量的数据,并且可以跨多个应用程序共享数据,但是它的缺点是需要额外的硬件和网络资源来支持,同时也存在单点故障的风险。为了解决这个问题,我们可以将Redis缓存和本地缓存结合使用,实现二级缓存。 具体实现方法如下: 1)创建Redis缓存客户端 java JedisPool jedisPool = new JedisPool("localhost", 6379); Jedis jedis = jedisPool.getResource(); 2)创建Guava本地缓存 java LoadingCache<String, Object> localCache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(new CacheLoader<String, Object>() { @Override public Object load(String key) throws Exception { // 从Redis缓存中加载数据 byte[] bytes = jedis.get(key.getBytes()); if (bytes != null) { return SerializationUtils.deserialize(bytes); } // 如果Redis缓存中没有数据,则从数据库或其他数据源中加载数据 return loadDataFromDatabase(key); } }); 3)在应用程序中使用二级缓存 java public Object getObject(String key) { Object value = null; try { // 先从本地缓存中获取数据 value = localCache.get(key); } catch (Exception e) { e.printStackTrace(); } if (value == null) { // 如果本地缓存中没有数据,则从Redis缓存中获取数据 byte[] bytes = jedis.get(key.getBytes()); if (bytes != null) { value = SerializationUtils.deserialize(bytes); // 将数据存储到本地缓存中 localCache.put(key, value); } } if (value == null) { // 如果Redis缓存中也没有数据,则从数据库或其他数据源中加载数据 value = loadDataFromDatabase(key); // 将数据存储到Redis缓存和本地缓存中 byte[] bytes = SerializationUtils.serialize(value); jedis.set(key.getBytes(), bytes); localCache.put(key, value); } return value; } 以上就是Guava和Redis实现二级缓存的方法。需要注意的是,二级缓存的实现需要综合考虑应用程序的性能、复杂度、可靠性和安全性等方面的因素,选择合适的缓存技术和策略,才能达到最优的效果。

最新推荐

Mybatis-plus基于redis实现二级缓存过程解析

主要介绍了Mybatis-plus基于redis实现二级缓存过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Java自定义注解实现Redis自动缓存的方法

本篇文章主要介绍了Java自定义注解实现Redis自动缓存的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

Redis缓存穿透,缓存击穿和缓存雪崩

二、缓存穿透,缓存击穿和缓存雪崩 缓存穿透 描述:缓存穿透是指缓存和数据库中都没有的数据,而用户不断发起请求,如发起为id为“-1024”的数据或id为特别大不存在的数据。这时的用户很可能是攻击者,攻击会导致...

Spring Cache手动清理Redis缓存

主要介绍了Spring Cache手动清理Redis缓存,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

java操作Redis缓存设置过期时间的方法

主要介绍了java操作Redis缓存设置过期时间的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

数据结构1800试题.pdf

你还在苦苦寻找数据结构的题目吗?这里刚刚上传了一份数据结构共1800道试题,轻松解决期末挂科的难题。不信?你下载看看,这里是纯题目,你下载了再来私信我答案。按数据结构教材分章节,每一章节都有选择题、或有判断题、填空题、算法设计题及应用题,题型丰富多样,共五种类型题目。本学期已过去一半,相信你数据结构叶已经学得差不多了,是时候拿题来练练手了,如果你考研,更需要这份1800道题来巩固自己的基础及攻克重点难点。现在下载,不早不晚,越往后拖,越到后面,你身边的人就越卷,甚至卷得达到你无法想象的程度。我也是曾经遇到过这样的人,学习,练题,就要趁现在,不然到时你都不知道要刷数据结构题好还是高数、工数、大英,或是算法题?学完理论要及时巩固知识内容才是王道!记住!!!下载了来要答案(v:zywcv1220)。

语义Web动态搜索引擎:解决语义Web端点和数据集更新困境

跟踪:PROFILES数据搜索:在网络上分析和搜索数据WWW 2018,2018年4月23日至27日,法国里昂1497语义Web检索与分析引擎Semih Yumusak†KTO Karatay大学,土耳其semih. karatay.edu.trAI 4 BDGmbH,瑞士s. ai4bd.comHalifeKodazSelcukUniversity科尼亚,土耳其hkodaz@selcuk.edu.tr安德烈亚斯·卡米拉里斯荷兰特文特大学utwente.nl计算机科学系a.kamilaris@www.example.com埃利夫·尤萨尔KTO KaratayUniversity科尼亚,土耳其elif. ogrenci.karatay.edu.tr土耳其安卡拉edogdu@cankaya.edu.tr埃尔多安·多杜·坎卡亚大学里扎·埃姆雷·阿拉斯KTO KaratayUniversity科尼亚,土耳其riza.emre.aras@ogrenci.karatay.edu.tr摘要语义Web促进了Web上的通用数据格式和交换协议,以实现系统和机器之间更好的互操作性。 虽然语义Web技术被用来语义注释数据和资源,更容易重用,这些数据源的特设发现仍然是一个悬 而 未 决 的 问 题 。 流 行 的 语 义 Web �

centos7安装nedit

### 回答1: 你可以按照以下步骤在 CentOS 7 上安装 nedit: 1. 打开终端并切换到 root 用户。 2. 运行以下命令安装 EPEL 存储库: ``` yum install epel-release ``` 3. 运行以下命令安装 nedit: ``` yum install nedit ``` 4. 安装完成后,你可以在终端中运行以下命令启动 nedit: ``` nedit ``` 如果你想打开一个文件,可以使用以下命令: ``` nedit /path/to/file

TFT屏幕-ILI9486数据手册带命令标签版.pdf

ILI9486手册 官方手册 ILI9486 is a 262,144-color single-chip SoC driver for a-Si TFT liquid crystal display with resolution of 320RGBx480 dots, comprising a 960-channel source driver, a 480-channel gate driver, 345,600bytes GRAM for graphic data of 320RGBx480 dots, and power supply circuit. The ILI9486 supports parallel CPU 8-/9-/16-/18-bit data bus interface and 3-/4-line serial peripheral interfaces (SPI). The ILI9486 is also compliant with RGB (16-/18-bit) data bus for video image display. For high speed serial interface, the ILI9486 also provides one data and clock lane and supports up to 500Mbps on MIPI DSI link. And also support MDDI interface.

数据搜索和分析

跟踪:PROFILES数据搜索:在网络上分析和搜索数据WWW 2018,2018年4月23日至27日,法国里昂1485表征数据集搜索查询艾米莉亚·卡普尔扎克英国南安普敦大学开放数据研究所emilia. theodi.org珍妮·坦尼森英国伦敦开放数据研究所jeni@theodi.org摘要在Web上生成和发布的数据量正在迅速增加,但在Web上搜索结构化数据仍然存在挑战。在本文中,我们探索数据集搜索分析查询专门为这项工作产生的通过众包-ING实验,并比较它们的搜索日志分析查询的数据门户网站。搜索环境的变化以及我们给人们的任务改变了生成的查询。 我们发现,在我们的实验中发出的查询比数据门户上的数据集的搜索查询要长得多。 它们还包含了七倍以上的地理空间和时间信息的提及,并且更有可能被结构化为问题。这些见解可用于根据数据集搜索的特定信息需求和特征关键词数据集搜索,�