springCloud中将redis共用到common模块

一、 springCloud作为公共模块搭建框架

springCloud 微服务模块中将redis作为公共模块进行的搭建结构图,如下:
在这里插入图片描述

二、redis 公共模块的搭建框架

在这里插入图片描述

  1. 如上架构,代码如下
  2. pom.xml 关键代码:
    <dependencies><!-- SpringBoot Boot Redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>2.5.1</version></dependency><dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>3.15.0</version></dependency></dependencies>   
  1. Redis使用FastJson序列化
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.util.Assert;
import java.nio.charset.Charset;/*** Redis使用FastJson序列化*/
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
{@SuppressWarnings("unused")private ObjectMapper objectMapper = new ObjectMapper();public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");private Class<T> clazz;static{ParserConfig.getGlobalInstance().setAutoTypeSupport(true);}public FastJson2JsonRedisSerializer(Class<T> clazz){super();this.clazz = clazz;}@Overridepublic byte[] serialize(T t) throws SerializationException{if (t == null){return new byte[0];}return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);}@Overridepublic T deserialize(byte[] bytes) throws SerializationException{if (bytes == null || bytes.length <= 0){return null;}String str = new String(bytes, DEFAULT_CHARSET);return JSON.parseObject(str, clazz);}public void setObjectMapper(ObjectMapper objectMapper){Assert.notNull(objectMapper, "'objectMapper' must not be null");this.objectMapper = objectMapper;}protected JavaType getJavaType(Class<?> clazz){return TypeFactory.defaultInstance().constructType(clazz);}
}
  1. redis 配置类
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.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;/*** redis配置*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);ObjectMapper mapper = new ObjectMapper();mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);serializer.setObjectMapper(mapper);// 使用StringRedisSerializer来序列化和反序列化redis的key值template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(serializer);// Hash的key也采用StringRedisSerializer的序列化方式template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(serializer);template.afterPropertiesSet();return template;}
}
  1. 读取springcloud 服务模块中的yml中配置的redis代码实体
    yml中的配置一般如下:
spring:redis:host: IP地址port: 6379password: 密码

之前连接redis代码中发现直接把账号和密码都写入模块了(可能当时为了方便)
这个造成如果地址发生变化需要不停的修改极其繁琐,索性将配置写入yml中,通过实体加配置ConfigurationProperties读取yml公用这样方便使用,起到了真正简化易改的作用

@Configuration
@RefreshScope
@Data
@ConfigurationProperties(prefix = "spring.redis")   //切记此处一定要加spring否则容易读不出来
public class RedisConn {@ApiModelProperty(value = "账号")private String host;@ApiModelProperty(value = "端口")private int port;@ApiModelProperty(value = "密码")private String password;
}
  1. redis 连接配置
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;import javax.annotation.Resource;
import java.io.IOException;@Configuration
public class RedssonConfig {@Bean@ConditionalOnMissingBeanpublic RedisConn getRedisConn(){return new RedisConn();}@Primary@Beanpublic RedissonClient redissonClient() throws IOException {Config config = new Config();RedisConn redisConn = getRedisConn();//此处就是redis实体读取yml中的地址和端口,简单方便连接String url = "redis://"+redisConn.getHost()+":"+redisConn.getPort();System.out.println("url:"+url);config.useSingleServer().setAddress(url).setPassword(redisConn.getPassword());RedissonClient redisson = Redisson.create(config);return redisson;}@Beanpublic RedissonClient shutdown(@Qualifier("redissonClient") RedissonClient redissonClient) {return redissonClient;}
}
  1. 以上redis 就配置完了,后续我们可以写reids的模版的进行缓存的增加,删除等操作了,这个是个我写的小模块,大家可以根据自己的需求添加,方便后续其他的springcloud模块调用的方式
import java.util.Collection;
import java.util.Iterator;
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.BoundSetOperations;
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;/*** spring redis 工具类**/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisService
{@Autowiredpublic 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 时间颗粒度*/public <T> void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit){redisTemplate.opsForValue().set(key, value, timeout, timeUnit);}/*** 设置有效时间** @param key Redis键* @param timeout 超时时间* @return true=设置成功;false=设置失败*/public boolean expire(final String key, final long timeout){return expire(key, timeout, TimeUnit.SECONDS);}/*** 设置有效时间** @param key Redis键* @param timeout 超时时间* @param unit 时间单位* @return true=设置成功;false=设置失败*/public boolean expire(final String key, final long timeout, final TimeUnit unit){return redisTemplate.expire(key, timeout, unit);}/*** 判断 key是否存在** @param key 键* @return true 存在 false不存在*/public Boolean hasKey(String key){return redisTemplate.hasKey(key);}/*** 获得缓存的基本对象。** @param key 缓存键值* @return 缓存键值对应的数据*/public <T> T getCacheObject(final String key){ValueOperations<String, T> operation = redisTemplate.opsForValue();return operation.get(key);}/*** 删除单个对象** @param key*/public boolean deleteObject(final String key){return redisTemplate.delete(key);}/*** 删除集合对象** @param collection 多个对象* @return*/public long deleteObject(final Collection collection){return redisTemplate.delete(collection);}
}
  1. 另外切记在spring.factories中进行注入哈

在这里插入图片描述

至此,这个redis的公共模块就完成了,大家可以直接在其他服务模块中将redis当成一个依赖添加到对应的服务的pom中即可如下:

   <dependency><groupId>com.(包名)</groupId><artifactId>common-redis</artifactId></dependency>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/22202.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Thread Local六连问,你扛得住吗?

一、Thread Local 是什么? 线程本地变量。当使用ThreadLocal维护变量时&#xff0c;ThreadLocal为每个使用该变量的线程提供独立的变量副本&#xff0c;所以每个线程都可以独立地改变自己的副本&#xff0c;而不影响其他线程&#xff0c;做到了线程隔离。 二、Thread Local …

windows hash简介

一、hash简介 1、Windows系统使用两种方法对用户的密码进行哈希处理。它们分别是LAN Manager(LM)哈希和 NT LAN Manager(NTLM)哈希 2、所谓哈希(hash)&#xff0c;就是使用一种加密函数进行计算后的结果。这个加密函数对一个任意长度的 字符串数据进行一次数学加密函数运算…

电厂三维人员定位系统的应用与优势有哪些?

在电力行业的快速发展中&#xff0c;电厂的安全生产和管理显得尤为重要。近年来&#xff0c;随着信息技术的不断进步&#xff0c;电厂三维人员定位系统逐渐成为电厂安全管理的新利器。该系统利用三维技术&#xff0c;实现对电厂内部人员位置的实时监控与定位&#xff0c;大大提…

图像操作的基石Numpy

OpenCV中用到的矩阵都要转换成Numpy数组 Numpy是一个经高度优化的Python数值库 创建矩阵 检索与赋值[y,x] 获取子数组[:,:] 一 创建数组array() anp.array([2,3,4]) cnp.array([1.0,2.0],[3.0,4.0]]) import numpy as npanp.array([1,2,3])bnp.array([[1,2,3],[4,5,6]])pr…

主机加固的最后一米防护

智慧互联的浪潮正席卷全球&#xff0c;它不仅重塑了传统的工业格局&#xff0c;也催生了无数创新的商业模式。随着物联网和互联网技术的飞速发展&#xff0c;智能化、自动化、联网化已成为未来各个行业的发展方向。然而&#xff0c;智慧物联的开放性、系统的漏洞以及基于用户、…

初识JAVA中的包装类,时间复杂度及空间复杂度

目录&#xff1a; 一.包装类 二.时间复杂度 三.空间复杂度 一.包装类&#xff1a; 在Java中&#xff0c;由于基本类型不是继承自Object&#xff0c;为了在泛型代码中可以支持基本类型&#xff0c;Java 给每个基本类型都对应了一个包装类型。 1 基本数据类型和对应的包装类 &am…

【Lua】IntelliJ IDEA 写注释或选中变量单词时偶尔会选中相邻的内容或下一行内容

例如: --UI代码local a 0 当你想在a变量上方加一行 --UI代码注释时&#xff0c;会发现敲打daima中文拼音时&#xff08;还未按回车&#xff09;就会选中当前行以及下一行前半部分。 打完按空格就会变成这样子&#xff01; 原因是因为开启了英文检测&#xff0c;需要关掉它。 …

一个http请求的前世今生

一个HTTP请求的“前世今生”可以被形象地描述为从发起请求到接收响应的整个生命周期。以下是这个过程的详细步骤&#xff1a; 用户输入URL&#xff1a; 用户在浏览器地址栏输入一个网址&#xff08;URL&#xff09;&#xff0c;这通常是一个网站的域名。 DNS解析&#xff1a;…

基于SVm和随机森林算法模型的中国黄金价格预测分析与研究

摘要 本研究基于回归模型&#xff0c;运用支持向量机&#xff08;SVM&#xff09;、决策树和随机森林算法&#xff0c;对中国黄金价格进行预测分析。通过历史黄金价格数据的分析和特征工程&#xff0c;建立了相应的预测模型&#xff0c;并利用SVM、决策树和随机森林算法进行训…

python_01

1、test # 方法1 不推荐使用&#xff0c;繁琐 # open("./1.txt",) # ./和不写&#xff0c;都代表从当前文件目录去找内容 file1 open(r".\1.txt","r",encoding"utf8") # "r" 读取 encoding"utf8" 设…

按按钮题解

推荐在 cnblogs 上阅读 按按钮题解 在量体温&#xff0c;打不了代码&#xff0c;来写题解。 赞美 lwq&#xff0c;三句话让我跟上了课堂节奏。 题意 数轴 n n n 个按钮&#xff0c;第 i i i 个按钮在坐标 i i i。有 m m m 次询问&#xff0c; i i i 询问为在时刻 t i…

英伟达驱动重装教程

离线安装NVIDIA驱动程序通常涉及下载驱动程序安装包并手动执行安装步骤。以下是详细步骤: 1. 下载NVIDIA驱动程序 首先,你需要在有网络连接的计算机上下载适合你系统的NVIDIA驱动程序安装包。可以从NVIDIA官方驱动下载页面下载。 选择你的GPU型号和操作系统,然后下载相应…

Gradio 案例——将文本文件转为词云图

文章目录 Gradio 案例——将文本文件转为词云图界面截图依赖安装项目目录结构代码 Gradio 案例——将文本文件转为词云图 利用 word_cloud 库&#xff0c;将文本文件转为词云图更完整、丰富的示例项目见 GitHub - AlionSSS/wordcloud-webui: The web UI for word_cloud(text t…

Python脚手架系列-PyQt5

记录PyQt模块使用中的一些常常复用的代码 其他 导入界面 import sysfrom PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication, QMainWindow from UI.MainWindow import Ui_MainWindow # 导入UI界面的类以供继承class MyApp(QMainWindow, Ui_MainWindow):de…

网络数据库后端面试题

接着上期 8&#xff0c;索引是怎么提高查询效率的&#xff0c;是不是多越好 索引是数据库中用来提高查询效率的技术&#xff0c;类似目录。如果不使用索引&#xff0c;数据会零散的保存在磁盘中&#xff0c;查询数据需要挨个遍历每一个磁盘块&#xff0c;直到找到数据&#…

未来以来!鸿蒙生态爆发式增长,程序员新出路火速Get。

鸿蒙生态取得爆发式增长&#xff01; 鸿蒙生态建设速度突飞猛进&#xff0c;不仅有超4000款应用加速开发&#xff0c;众多头部SDK伙伴也在积极加入&#xff0c;为开发者提供构建鸿蒙原生应用所需的多项能力。近期&#xff0c;友盟移动统计SDK、神策数据SDK、阿里云日志服务SDK…

【Vue】v-bind对样式控制的增强-操作class

文章目录 一、语法二、示例代码三、京东秒杀-tab栏切换导航高亮四、v-bind对有样式控制的增强-操作style五、进度条案例 为了方便开发者进行样式控制&#xff0c; Vue 扩展了 v-bind 的语法&#xff0c;可以针对 class 类名 和 style 行内样式 进行控制 。 一、语法 语法 &l…

Latex中标注通讯作者

** 直接使用脚注&#xff0c;不用添加宏包 多个同地址的并列&#xff0c;建议加点空格&#xff0c;好看一些 ** \title{xxxxxxxxxxxxxxxxxxx}\author{xxxxxxxxxxxxxxxxxxx\footnote{Corresponding author} ,bbbbbbbbbbbbbbbbbbb}\address{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx…

免费,Scratch蓝桥杯比赛历年真题--第15届蓝桥杯STEMA真题-2024年3月份(含答案解析和代码)

第15届蓝桥杯STEMA真题-2024年3月份 一、单选题 答案&#xff1a;D 解析&#xff1a;y坐标正值表示上&#xff0c;负值表示下&#xff0c;故答案为D。 答案&#xff1a;C 解析&#xff1a;18<25为真&#xff0c;或关系表示一真即为真&#xff0c;故答案为C。 答案&#xff…

Android设备获取OAID调研和实现

什么是OAID、AAID、VAID OAID OAID是"Android ID"&#xff08;安卓ID&#xff09;的一种替代方案&#xff0c;其全称为"Open Anonymous Identifier"&#xff08;开放匿名标识符&#xff09;。 因传统的移动终端设备标识如国际移动设备识别码&#xff08;…