写一个mybatisplus用redis做二级缓存的代码

时间: 2023-05-25 11:04:52 浏览: 35
以下是一个使用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注解进行数据的缓存和查询,同时要保证实体类的序列化和反序列化能够正确进行。

相关推荐

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 中。这样可以大大提高查询效率,减轻数据库负担。
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二级缓存默认使用了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配置文件中定义的缓存名称一致,否则设置无效。
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方法中添加分布式锁逻辑。
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)
非常感谢您的提问。以下是 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 实现二级缓存的具体步骤和代码。希望能对您有所帮助!
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); }
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缓存管理器,但是有时候我们需要根据自己的业务需求来定制一个适合自己的缓存管理器,这里简单介绍一下如何自定义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缓存管理器进行缓存。
当然,我可以为您提供一个Java代码示例,用于实现Redis缓存延迟双删。以下是代码示例: java public class RedisCache { private static final Logger logger = LoggerFactory.getLogger(RedisCache.class); private RedisTemplate<String, Object> redisTemplate; public RedisCache(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } public Object get(String key) { return redisTemplate.opsForValue().get(key); } public void put(String key, Object value, long expireTime) { redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS); } public void delete(String key) { redisTemplate.delete(key); } public void deleteWithDelay(String key, long delayTime) { redisTemplate.expire(key, delayTime, TimeUnit.SECONDS); Executors.newSingleThreadScheduledExecutor().schedule(() -> { if (redisTemplate.hasKey(key)) { redisTemplate.delete(key); logger.info("Redis key {} has been deleted with delay {} seconds", key, delayTime); } }, delayTime, TimeUnit.SECONDS); } } 在这个示例中,我们创建了一个名为RedisCache的类,它使用了Spring Data Redis提供的RedisTemplate来操作Redis缓存。该类包含了get、put、delete和deleteWithDelay方法,其中deleteWithDelay方法实现了Redis缓存延迟双删的功能。 在deleteWithDelay方法中,我们首先使用RedisTemplate的expire方法设置了key的过期时间,然后使用ScheduledExecutorService来延迟执行删除操作。如果在延迟时间到达之前,key已经被删除了,那么我们就不需要再执行删除操作了。 希望这个示例能够帮助您实现Redis缓存延迟双删。
好的,以下是一个简单的 Spring Redis 缓存注解: java @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface RedisCache { String key() default ""; // 缓存键值 String field() default ""; // 缓存字段,用于 Hash long expire() default 60; // 缓存过期时间,默认60秒 Class<?> type() default Object.class; // 缓存对象类型,默认为 Object 类型 } 注解的作用是将方法的执行结果缓存到 Redis 中,下次执行方法时可以直接从缓存中获取结果,避免重复计算。 使用示例: java @Service public class MyService { @Autowired private RedisTemplate<String, Object> redisTemplate; @RedisCache(key = "myKey", expire = 300) public Object getData(String param1, int param2) { // 从数据库或其他服务获取数据 Object data = getDataFromOtherService(param1, param2); return data; } private Object getDataFromOtherService(String param1, int param2) { // ... } } 在上面的例子中,MyService 的 getData 方法被加上了 @RedisCache 注解,表示该方法的执行结果需要缓存到 Redis 中。key 参数指定了缓存的键值,这里设置为 myKey,expire 参数指定了缓存的过期时间,这里设置为 300 秒(即 5 分钟)。当 getData 方法第一次被调用时,会先从 Redis 中查询缓存,如果缓存中没有对应的结果,则执行 getDataFromOtherService 方法获取数据,并将结果缓存到 Redis 中。下次再调用 getData 方法时,会直接从 Redis 中获取缓存结果。 需要注意的是,使用 Redis 缓存需要先配置 RedisTemplate,这里省略了配置代码。另外,该注解只适用于方法返回值为 Object 类型的情况,如果要支持其他类型的返回值,需要修改注解中的 type 参数。
1. 添加Redis依赖 在pom.xml中添加以下依赖: xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 2. 配置Redis 在application.properties中添加Redis配置: properties # Redis配置 spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= # Redis密码(如果需要) 3. 编写缓存操作类 创建一个类RedisCacheService,用于实现缓存的操作: java @Service public class RedisCacheService { @Autowired private RedisTemplate<String, Object> redisTemplate; /** * 获取缓存数据 * * @param key 缓存的key * @return 缓存的value */ public Object get(String key) { return redisTemplate.opsForValue().get(key); } /** * 设置缓存数据 * * @param key 缓存的key * @param value 缓存的value * @param time 过期时间(单位:秒) */ public void set(String key, Object value, long time) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } /** * 删除缓存数据 * * @param key 缓存的key */ public void delete(String key) { redisTemplate.delete(key); } } 4. 编写控制器 创建一个控制器RedisCacheController,用于测试缓存的操作: java @RestController public class RedisCacheController { @Autowired private RedisCacheService redisCacheService; @GetMapping("/set") public String set() { redisCacheService.set("name", "test", 60); return "OK"; } @GetMapping("/get") public String get() { Object value = redisCacheService.get("name"); return value != null ? value.toString() : "NULL"; } @GetMapping("/delete") public String delete() { redisCacheService.delete("name"); return "OK"; } } 5. 启动应用程序 启动应用程序,访问http://localhost:8080/set设置缓存数据,访问http://localhost:8080/get获取缓存数据,访问http://localhost:8080/delete删除缓存数据。可以通过Redis客户端查看缓存数据是否被正确设置、获取、删除。
以下是使用C语言读取Redis数据库中某个键值的示例代码: c #include <stdio.h> #include <stdlib.h> #include <hiredis/hiredis.h> // Redis C客户端库 int main() { redisContext *c; redisReply *reply; const char *hostname = "localhost"; // Redis服务器地址 int port = 6379; // Redis服务器端口号 const char *password = "yourpassword"; // Redis连接密码,如果没有密码则可以置为NULL const char *key = "yourkey"; // 要读取的Redis键值 // 连接Redis服务器 c = redisConnect(hostname, port); if (c == NULL || c->err) { if (c) { printf("Error: %s\n", c->errstr); redisFree(c); } else { printf("Can't allocate redis context\n"); } exit(1); } // 如果需要验证密码,使用AUTH命令进行认证 if (password != NULL) { reply = redisCommand(c, "AUTH %s", password); if (reply == NULL || reply->type == REDIS_REPLY_ERROR) { printf("Error: %s\n", reply == NULL ? "NULL reply" : reply->str); freeReplyObject(reply); redisFree(c); exit(1); } freeReplyObject(reply); } // 使用GET命令获取键值 reply = redisCommand(c, "GET %s", key); if (reply == NULL || reply->type == REDIS_REPLY_NIL) { printf("Key does not exist or has no value\n"); } else if (reply->type == REDIS_REPLY_STRING) { printf("Value: %s\n", reply->str); } else { printf("Invalid reply type: %d\n", reply->type); } freeReplyObject(reply); // 关闭Redis连接 redisFree(c); return 0; } 请将上述代码保存到文件中并编译运行即可。需要注意的是,本示例代码使用了 hiredis 库来访问 Redis,因此需要先安装该库才能正常编译运行。

最新推荐

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

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

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

处理Reids缓存引发的问题时,我们首先得知道缓存处理的一个流程,如下图: 二、缓存穿透,缓存击穿和缓存雪崩 缓存穿透 描述:缓存穿透是指缓存和数据库中都没有的数据,而用户不断发起请求,如发起为id为“-1024”...

Spring Boot中使用Redis做缓存的方法实例

主要给大家介绍了关于Spring Boot中使用Redis做缓存的相关资料,文中介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来一起看看吧。

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实验,并比较它们的搜索日志分析查询的数据门户网站。搜索环境的变化以及我们给人们的任务改变了生成的查询。 我们发现,在我们的实验中发出的查询比数据门户上的数据集的搜索查询要长得多。 它们还包含了七倍以上的地理空间和时间信息的提及,并且更有可能被结构化为问题。这些见解可用于根据数据集搜索的特定信息需求和特征关键词数据集搜索,�