应用场景:
保存大数据量,避免重复请求。
一、添加Maven依赖
<!-- SpringBoot Boot Redis --><dependency> <groupID>org.springframework.boot</groupID> <artifactID>spring-boot-starter-data-redis</artifactID></dependency>二、编写Redis相关类
RedisService.java
import java.util.Collection;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;import org.springframework.beans.factory.annotation.autowired;import org.springframework.data.redis.core.HashOperations;import org.springframework.data.redis.core.Redistemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Component;@SuppressWarnings(value = { "unchecked",rawtypes" })@Componentpublic class RedisService{ @autowired public Redistemplate redistemplate; /** * 缓存基本的对象,Integer、String、实体类等 * * @param key 缓存的键值 * @param value 缓存的值 */ public <T> voID setCacheObject(final String key,final T value) { redistemplate.opsForValue().set(key,value); } * * 缓存基本的对象,Integer、String、实体类等 * * @param key 缓存的键值 * @param value 缓存的值 * @param timeout 时间 * @param timeUnit 时间颗粒度 * * 设置有效时间 * * @param key Redis键 * @param timeout 超时时间 * @return true=设置成功;false=设置失败 public boolean expire(final String key,final long timeout) { return expire(key,TimeUnit.SECONDS); } * * 设置有效时间 * * @param key Redis键 * @param timeout 超时时间 * @param unit 时间单位 * @return true=设置成功;false=设置失败 timeout,final TimeUnit unit) { redistemplate.expire(key,unit); } * * 获得缓存的基本对象。 * * @param key 缓存键值 * @return 缓存键值对应的数据 public <T> T getCacheObject(final String key) { ValueOperations<String,T> operation = redistemplate.opsForValue(); return operation.get(key); } * * 删除单个对象 * * @param key boolean deleteObject(final String key) { redistemplate.delete(key); } * * 删除集合对象 * * @param collection 多个对象 * @return deleteObject(final Collection collection) { redistemplate.delete(collection); } * * 缓存List数据 * * @param key 缓存的键值 * @param dataList 待缓存的List数据 * @return 缓存的对象 long setCacheList(final String key,final List<T> dataList) { Long count = redistemplate.opsForList().rightPushAll(key,dataList); return count == null ? 0 : count; } * * 获得缓存的List对象 * * @param key 缓存的键值 * @return 缓存键值对应的数据 public <T> List<T> getCacheList(final String key) { return redistemplate.opsForList().range(key,1)">0,-1); } * * 缓存Set * * @param key 缓存键值 * @param dataSet 缓存的数据 * @return 缓存数据的对象 long setCacheSet(final String key,final Set<T> dataSet) { Long count = redistemplate.opsForSet().add(key,dataSet); * * 获得缓存的set * * @param key * @return public <T> Set<T> getCacheSet(final String key) { redistemplate.opsForSet().members(key); } * * 缓存Map * * @param key * @param dataMap voID setCacheMap(final String key,final Map<String,T> dataMap) { if (dataMap != null) { redistemplate.opsForHash().putAll(key,dataMap); } } * * 获得缓存的Map * * @param key * @return public <T> Map<String,1)"> getCacheMap(final String key) { redistemplate.opsForHash().entrIEs(key); } * * 往Hash中存入数据 * * @param key Redis键 * @param hKey Hash键 * @param value 值 setCacheMapValue(final String key,final String hKey,final T value) { redistemplate.opsForHash().put(key,hKey,1)">* * 获取Hash中的数据 * * @param key Redis键 * @param hKey Hash键 * @return Hash中的对象 T getCacheMapValue(final String key,final String hKey) { HashOperations<String,String,T> opsForHash = redistemplate.opsForHash(); return opsForHash.* * 获取多个Hash中的数据 * * @param key Redis键 * @param hKeys Hash键集合 * @return Hash对象集合 public <T> List<T> getMultiCacheMapValue(final String key,final Collection<Object> hKeys) { redistemplate.opsForHash().multiGet(key,hKeys); } * * 获得缓存的基本对象列表 * * @param pattern 字符串前缀 * @return 对象列表 public Collection<String> keys(final String pattern) { redistemplate.keys(pattern); }}
RedisConfig.java
import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.Redistemplate;import org.springframework.data.redis.serializer.StringRedisSerializer;import com.fasterxml.jackson.annotation.JsonautoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;@Configuration@EnableCaching RedisConfig extends CachingConfigurerSupport{ @Bean @SuppressWarnings(value = { deprecation }) public Redistemplate<Object,Object> redistemplate(RedisConnectionFactory connectionFactory) { Redistemplate<Object,Object> template = new Redistemplate<>(); template.setConnectionFactory(connectionFactory); FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL,JsonautoDetect.Visibility.ANY); mapper.enableDefaultTyPing(ObjectMapper.DefaultTyPing.NON_FINAL); serializer.setobjectMapper(mapper); template.setValueSerializer(serializer); // 使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer( StringRedisSerializer()); template.afterPropertIEsSet(); template; }}
RedisCache.java
import org.apache.ibatis.cache.Cache;import org.springframework.data.redis.core.RedisCallback;import org.springframework.data.redis.core.Redistemplate;import org.springframework.data.redis.core.ValueOperations;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.ReaDWriteLock;import java.util.concurrent.locks.reentrantreadwritelock; RedisCache implements Cache { private final ReaDWriteLock reaDWriteLock = reentrantreadwritelock(); private final String ID; Redistemplate redistemplate; redis过期时间 private static final long EXPIRE_TIME_IN_MINUTES = 30; RedisCache(String ID) { if (ID == ) { throw new IllegalArgumentException(Cache instance required an ID); } this.ID = ID; } @OverrIDe String getID() { ID; } * * Put query result to redis * * @Param key * @Param value */ @OverrIDe putObject(Object key,Object value) { Redistemplate redistemplate = getRedistemplate(); ValueOperations opsForValue = redistemplate.opsForValue(); System.out.println(key + : key); System.out.println(key.toString() + : key.toString()out.println(value + : valueout.println(value.toString() + : value.toString()); opsForValue.(key.toString(),EXPIRE_TIME_IN_MINUTES,TimeUnit.MINUTES); System.out.println(结果成功放入缓存 and " + key = \n" + key + value = " + value); System.out.println(opsForValue.(key.toString())); } * * Get cached query result to redis * * @Param key * @Return Object getobject(Object key) { Redistemplate redistemplate = getRedistemplate(); redistemplate.setHashValueSerializer(new StringRedisSerializer()); ValueOperations opsForValue =结果从缓存中获取); return opsForValue.(key.toString()); } * * Remove cached query result to redis * * @Param key * @Return Object removeObject(Object key) { Redistemplate redistemplate = getRedistemplate(); redistemplate.delete(key); System.从缓存中删除return ; } * * Clear this cache instance clear() { Redistemplate redistemplate = getRedistemplate(); redistemplate.execute((RedisCallback) connection -> { connection.flushDb(); ; }); System.清空缓存); } @OverrIDe int getSize() { Long size = (Long) redistemplate.execute((RedisCallback) connection -> connection.dbSize()); size.intValue(); } @OverrIDe ReaDWriteLock getReaDWriteLock() { reaDWriteLock; } Redistemplate getRedistemplate() { if (redistemplate == ) { redistemplate = ApplicationContextHolder.getBean(redistemplate redistemplate; }}三、yml配置redis
spring: redis: host: localhost port: 6379 password:四、在DAO类添加该注解
@Cachenamespace(implementation = RedisCache.class)
五、实现类或者在Controller加如下代码,键值对保存对应的数据@autowiredprivate RedisService redisService;
六、如何确保Redis数据实时更新
我研究了下,通常如下:
1.先删缓存,再更新数据库
2.先写数据库,再删缓存
参考:
Redis缓存如何保证一致性
补充:
Redis 和 Mysql 数据库数据如何保持一致性
以上是内存溢出为你收集整理的SpringBoot+MyBatis+Redis(二级缓存)全部内容,希望文章能够帮你解决SpringBoot+MyBatis+Redis(二级缓存)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)