现在的位置: 首页 > 编程语言 > 正文

SpringBootredis分布式缓存实现过程解析

2020年02月13日 编程语言 ⁄ 共 15591字 ⁄ 字号 评论关闭

前言

应用系统需要通过Cache来缓存不经常改变得数据来提高系统性能和增加系统吞吐量,避免直接访问数据库等低速存储系统。缓存的数据通常存放在访问速度更快的内存里或者是低延迟存取的存储器,服务器上。应用系统缓存,通常有如下作用:缓存web系统的输出,如伪静态页面。缓存系统的不经常改变的业务数据,如用户权限,字典数据.配置信息等

大家都知道springBoot项目都是微服务部署,A服务和B服务分开部署,那么它们如何更新或者获取共有模块的缓存数据,或者给A服务做分布式集群负载,如何确保A服务的所有集群都能同步公共模块的缓存数据,这些都涉及到分布式系统缓存的实现。(ehcache可以通过Terracotta组件一个缓存集群,这个暂时不讲)

但是ehcache的设计并不适合做分布式缓存,所以今天用redis来实现分布式缓存。

架构图:

一二级缓存服务器

使用Redis缓存,通过网络访问还是不如从内存中获取性能好,所以通常称之为二级缓存,从内存中取得的缓存数据称之为一级缓存。当应用系统需要查询缓存的时候,先从一级缓存里查找,如果有,则返回,如果没有查找到,则再查询二级缓存,架构图如下

Spring Boot 2 自带了前面俩种缓存的实现方式,本文将简单实现第三种,高速一二级缓存实现

Redis分布式缓存

引入redis的starter

配置Redis

在application.yml中配置redis信息

spring: redis: database: 0 host: 192.168.0.146 port: 6379 timeout: 5000

其他相关配置

# Redis数据库索引(默认为0)spring.redis.database=0 # Redis服务器地址spring.redis.host=127.0.0.1# Redis服务器连接端口spring.redis.port=6379 # Redis服务器连接密码(默认为空)spring.redis.password=# 连接池最大连接数(使用负值表示没有限制)spring.redis.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接spring.redis.pool.max-idle=8 # 连接池中的最小空闲连接spring.redis.pool.min-idle=0 # 连接超时时间(毫秒)spring.redis.timeout=0

配置Redis缓存序列化机制

有的时候需要将对象存进redis(例如一个JavaBean对象),但是如果对象不是可Serializable的,因此需要让JavaBean对象实现Serializable接口

public class UserPO implements Serializable {

如果只是让JavaBean实现Serializable接口也是可以存储的,但是并不好看,那么能不能将JavaBean弄成Json的样式放进redis呢。直接的方式就是自己转换,但是未免有点麻烦,那就只能修改RedisTemplate的序列化机制了,在配置类中配置上序列化的方法即可

@Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate(); template.setConnectionFactory(factory); Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // 值采用json序列化 template.setValueSerializer(jacksonSeial); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); return template; }

自定义CacheManager

/** * 选择Redis作为默认缓存工具 * @param redisTemplate * @return */ @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); return RedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); }

RedisConfig完整代码

import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.interceptor.KeyGenerator;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheConfiguration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.cache.RedisCacheWriter;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer; import java.lang.reflect.Method;import java.net.UnknownHostException; @Configurationpublic class RedisConfig extends CachingConfigurerSupport { /** * 选择Redis作为默认缓存工具 * @param redisTemplate * @return */ @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); return RedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); } /** * retemplate相关配置(序列化机制对象) * @param factory * @return */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate(); // 配置连接工厂 template.setConnectionFactory(factory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式) Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // 值采用json序列化 template.setValueSerializer(jacksonSeial); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); // 设置hash key 和value序列化模式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); return template; } /** * 自定义key的生成策略 * @return */ @Bean public KeyGenerator myKeyGenerator(){ return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; }}

使用Redi缓存注解

service:

@CachePut(value = "user",key = "'user_'+#result.id") public UserPO save(UserPO po) { userJpaMapper.save(po); return po; } @CachePut(value = "user",key = "'user_'+#result.id") public UserPO update(UserPO po) { System.out.println("数据库更新"); userMapper.update(po); return po; } @Cacheable(value = "user", key = "'user_'+#id") public UserPO getUser(Integer id){ System.out.println("访问数据库:"+id); return userJpaMapper.getOne(id); } @CacheEvict(value = "user", key = "'user_'+#id") public void delete(Integer id) { userJpaMapper.deleteById(id); }

测试类:

@Test void contextLoads() { Integer id = 2; UserPO user1 = userService.getUser(id); System.out.println("第一次查询:"+user1.getUserName()); UserPO user2 = userService.getUser(id); System.out.println("第二次查询:"+user2.getUserName()); }

测试结果:第一次查询的时候访问了数据库,第二次查询的时候并没有访问数据库

通过redis-cli 可以查看到数据已经保存到了redis上面

测试类:

@Test void updataUser() { Integer id = 4; UserPO user1 = userService.getUser(id); System.out.println("第一次查询:"+user1.getUserName()+", 年龄:"+user1.getAge()); user1.setAge(60); userService.update(user1); UserPO user2 = userService.getUser(id); System.out.println("第二次查询:"+user2.getUserName()+", 年龄:"+user2.getAge()); }

测试结果:

Redis工具类(redisUtil.java)

1.在RedisConfig中定义redisTemplate操作对象

/** * 对hash类型的数据操作 * @param redisTemplate * @return */ @Bean public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForHash(); } /** * 对redis字符串类型数据操作 * @param redisTemplate * @return */ @Bean public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForValue(); } /** * 对链表类型的数据操作 * @param redisTemplate * @return */ @Bean public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForList(); } /** * 对无序集合类型的数据操作 * @param redisTemplate * @return */ @Bean public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForSet(); } /** * 对有序集合类型的数据操作 * @param redisTemplate * @return */ @Bean public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForZSet(); }

2.在redisUtil工具类中使用这些对象,并构建其操作方法

package com.meng.demo.utils; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.*;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils; import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit; /** * redis工具类 */@Componentpublic class RedisUtil { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private ValueOperations<String, Object> valueOperations; @Autowired private HashOperations<String, String, Object> hashOperations; @Autowired private ListOperations<String, Object> listOperations; @Autowired private SetOperations<String, Object> setOperations; @Autowired private ZSetOperations<String, Object> zSetOperations; /**=============================共同操作============================*/ /** * 指定缓存失效时间 * @param key 键 * @param time 时间(秒) * @return */ public boolean expire(String key,long time){ try { if(time>0){ redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据key 获取过期时间 * @param key 键不能为null * @return 时间(秒) 返回0代表为永久有效 */ public long getExpire(String key){ return redisTemplate.getExpire(key,TimeUnit.SECONDS); } /** * 判断key是否存在 * @param key 键 * @return true-存在、false-不存在 */ public boolean hasKey(String key){ try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除缓存 * @param key 可以传一个值或多个 */ public void del(String ... key){ if(key!=null&&key.length>0){ if(key.length==1){ redisTemplate.delete(key[0]); }else{ redisTemplate.delete(CollectionUtils.arrayToList(key)); } } } /**============================ValueOperations操作=============================*/ /** * 普通缓存放入 * @param key 键 * @param value 值 * @return true-成功、 false-失败 */ public boolean set(String key,Object value) { try { valueOperations.set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 普通缓存放入并设置时间 * @param key 键 * @param value 值 * @param expireTime 时间(秒) expireTime要大于0 如果expireTime小于等于0 将设置无限期 * @return true成功 false失败 */ public boolean set(String key,Object value,long expireTime){ try { if(expireTime > 0){ valueOperations.set(key, value, expireTime, TimeUnit.SECONDS); }else{ set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 普通缓存获取 * @param key 键 * @return 值 */ public Object get(String key){ return key==null ? null:valueOperations.get(key); } /** * 递增 * @param key 键 * @return */ public long incr(String key, long delta){ if(delta<0){ throw new RuntimeException("递增因子必须大于0"); } return valueOperations.increment(key, delta); } /** * 递减 * @param key * @param delta 要减少几(小于0) * @return */ public long decr(String key, long delta){ if(delta<0){ throw new RuntimeException("递减因子必须大于0"); } return valueOperations.increment(key, -delta); } /**================================HashOperations操作=================================*/ /** * HashGet * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public Object hget(String key,String item){ return hashOperations.get(key, item); } /** * 获取hashKey对应的所有键值 * @param key 键 * @return 对应的多个键值 */ public Map<String, Object> hmget(String key){ return hashOperations.entries(key); } /** * HashSet * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map<String,Object> map){ try { hashOperations.putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet 并设置时间 * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 */ public boolean hmset(String key, Map<String,Object> map, long time){ try { hashOperations.putAll(key, map); if(time>0){ expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * @param key 键 * @param item 项 * @param value 值 * @return true 成功 false失败 */ public boolean hset(String key,String item,Object value) { try { hashOperations.put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * @param key 键 * @param item 项 * @param value 值 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 * @return true 成功 false失败 */ public boolean hset(String key,String item,Object value,long time) { try { hashOperations.put(key, item, value); if(time>0){ expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除hash表中的值 * @param key 键 不能为null * @param item 项 可以使多个 不能为null */ public void hdel(String key, Object... item){ hashOperations.delete(key,item); } /** * 判断hash表中是否有该项的值 * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item){ return hashOperations.hasKey(key, item); } /** * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * @param key 键 * @param item 项 * @param by 要增加几(大于0) * @return */ public double hincr(String key, String item,double by){ return hashOperations.increment(key, item, by); } /** * hash递减 * @param key 键 * @param item 项 * @param by 要减少记(小于0) * @return */ public double hdecr(String key, String item,double by){ return hashOperations.increment(key, item,-by); } /**============================set============================= /** * 根据key获取Set中的所有值 * @param key 键 * @return */ public Set<Object> sGet(String key){ try { return setOperations.members(key); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 根据value从一个set中查询,是否存在 * @param key 键 * @param value 值 * @return true 存在 false不存在 */ public boolean sHasKey(String key,Object value){ try { return setOperations.isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将数据放入set缓存 * @param key 键 * @param values 值 可以是多个 * @return 成功个数 */ public long sSet(String key, Object...values) { try { return setOperations.add(key, values); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 将set数据放入缓存 * @param key 键 * @param time 时间(秒) * @param values 值 可以是多个 * @return 成功个数 */ public long sSetAndTime(String key,long time,Object...values) { try { Long count = setOperations.add(key, values); if(time>0){ expire(key, time); } return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 获取set缓存的长度 * @param key 键 * @return */ public long sGetSetSize(String key){ try { return setOperations.size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 移除值为value的 * @param key 键 * @param values 值 可以是多个 * @return 移除的个数 */ public long setRemove(String key, Object ...values) { try { Long count = setOperations.remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /**===============================ListOperations================================= /** * 获取list缓存的内容 * @param key 键 * @param start 开始 * @param end 结束 0 到 -1代表所有值 * @return */ public List<Object> lGet(String key, long start, long end){ try { return listOperations.range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取list缓存的所有内容 * @param key * @return */ public List<Object> lGetAll(String key){ return lGet(key,0,-1); } /** * 获取list缓存的长度 * @param key 键 * @return */ public long lGetListSize(String key){ try { return listOperations.size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 通过索引 获取list中的值 * @param key 键 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推 * @return */ public Object lGetIndex(String key,long index){ try { return listOperations.index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将list放入缓存 * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, Object value) { try { listOperations.rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, Object value, long time) { try { listOperations.rightPush(key, value); if (time > 0){ expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, List<Object> value) { try { listOperations.rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, List<Object> value, long time) { try { listOperations.rightPushAll(key, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据索引修改list中的某条数据 * @param key 键 * @param index 索引 * @param value 值 * @return */ public boolean lUpdateIndex(String key, long index,Object value) { try { listOperations.set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 移除N个值为value * @param key 键 * @param count 移除多少个 * @param value 值 * @return 移除的个数 */ public long lRemove(String key,long count,Object value) { try { Long remove = listOperations.remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } }}

3.测试

@Test void test01(){ redisUtil.set("meng","yang"); Object key = redisUtil.get("meng"); System.out.println(key); }

 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: SpringBoot redis分布式缓存实现过程解析

以上就上有关SpringBootredis分布式缓存实现过程解析的相关介绍,要了解更多springboot,redis,分布式,缓存内容请登录学步园。

抱歉!评论已关闭.