电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Springboot整合Netty實現RPC服務器的示例代碼

瀏覽:7日期:2023-03-30 17:51:24
一、什么是RPC?

RPC(Remote Procedure Call)遠程過程調用,是一種進程間的通信方式,其可以做到像調用本地方法那樣調用位于遠程的計算機的服務。其實現的原理過程如下:

本地的進程通過接口進行本地方法調用。 RPC客戶端將調用的接口名、接口方法、方法參數等信息利用網絡通信發送給RPC服務器。 RPC服務器對請求進行解析,根據接口名、接口方法、方法參數等信息找到對應的方法實現,并進行本地方法調用,然后將方法調用結果響應給RPC客戶端。二、實現RPC需要解決那些問題?1. 約定通信協議格式

RPC分為客戶端與服務端,就像HTTP一樣,我們需要定義交互的協議格式。主要包括三個方面:

請求格式 響應格式 網絡通信時數據的序列化方式

RPC請求

@Datapublic class RpcRequest { /** * 請求ID 用來標識本次請求以匹配RPC服務器的響應 */ private String requestId; /** * 調用的類(接口)權限定名稱 */ private String className; /** * 調用的方法名 */ private String methodName; /** * 方法參類型列表 */ private Class<?>[] parameterTypes; /** * 方法參數 */ private Object[] parameters;}

RPC響應

@Datapublic class RpcResponse { /** * 響應對應的請求ID */ private String requestId; /** * 調用是否成功的標識 */ private boolean success = true; /** * 調用錯誤信息 */ private String errorMessage; /** * 調用結果 */ private Object result;}2. 序列化方式

序列化方式可以使用JDK自帶的序列化方式或者一些第三方的序列化方式,JDK自帶的由于性能較差所以不推薦。我們這里選擇JSON作為序列化協議,即將請求和響應對象序列化為JSON字符串后發送到對端,對端接收到后反序列為相應的對象,這里采用阿里的 fastjson 作為JSON序列化框架。

3. TCP粘包、拆包

TCP是個“流”協議,所謂流,就是沒有界限的一串數據。大家可以想想河里的流水,是連成一片的,其間并沒有分界線。TCP底層并不了解上層業務數據的具體含義,它會根據TCP緩沖區的實際情況進行包的劃分,所以在業務上認為,一個完整的包可能會被TCP拆分成多個包進行發送,也有可能把多個小的包封裝成一個大的數據包發送,這就是所謂的TCP粘包和拆包問題。粘包和拆包需要應用層程序來解決。

我們采用在請求和響應的頭部保存消息體的長度的方式解決粘包和拆包問題。請求和響應的格式如下:

+--------+----------------+ | Length | Content | | 4字節 | Length個字節 | +--------+----------------+4. 網絡通信框架的選擇

出于性能的考慮,RPC一般選擇異步非阻塞的網絡通信方式,JDK自帶的NIO網絡編程操作繁雜,Netty是一款基于NIO開發的網絡通信框架,其對java NIO進行封裝對外提供友好的API,并且內置了很多開箱即用的組件,如各種編碼解碼器。所以我們采用Netty作為RPC服務的網絡通信框架。

三、RPC服務端

RPC分為客戶端和服務端,它們有一個共同的服務接口API,我們首先定義一個接口 HelloService

public interface HelloService { String sayHello(String name);}

然后服務端需要提供該接口的實現類,然后使用自定義的@RpcService注解標注,該注解擴展自@Component,被其標注的類可以被Spring的容器管理。

@RpcServicepublic class HelloServiceImp implements HelloService { @Override public String sayHello(String name) { return 'Hello ' + name; }}

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Componentpublic @interface RpcService { }

RPC服務器類

我們實現了ApplicationContextAware接口,以便從bean容器中取出@RpcService實現類,存入我們的map容器中。

@Component@Slf4jpublic class RpcServer implements ApplicationContextAware, InitializingBean { // RPC服務實現容器 private Map<String, Object> rpcServices = new HashMap<>(); @Value('${rpc.server.port}') private int port; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { Map<String, Object> services = applicationContext.getBeansWithAnnotation(RpcService.class); for (Map.Entry<String, Object> entry : services.entrySet()) { Object bean = entry.getValue(); Class<?>[] interfaces = bean.getClass().getInterfaces(); for (Class<?> inter : interfaces) { rpcServices.put(inter.getName(), bean); } } log.info('加載RPC服務數量:{}', rpcServices.size()); } @Override public void afterPropertiesSet() { start(); } private void start(){ new Thread(() -> { EventLoopGroup boss = new NioEventLoopGroup(1); EventLoopGroup worker = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new IdleStateHandler(0, 0, 60));pipeline.addLast(new JsonDecoder());pipeline.addLast(new JsonEncoder());pipeline.addLast(new RpcInboundHandler(rpcServices)); } }) .channel(NioServerSocketChannel.class); ChannelFuture future = bootstrap.bind(port).sync(); log.info('RPC 服務器啟動, 監聽端口:' + port); future.channel().closeFuture().sync(); }catch (Exception e){ e.printStackTrace(); boss.shutdownGracefully(); worker.shutdownGracefully(); } }).start(); }}

RpcServerInboundHandler 負責處理RPC請求

@Slf4jpublic class RpcServerInboundHandler extends ChannelInboundHandlerAdapter { private Map<String, Object> rpcServices; public RpcServerInboundHandler(Map<String, Object> rpcServices){ this.rpcServices = rpcServices; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { log.info('客戶端連接成功,{}', ctx.channel().remoteAddress()); } public void channelInactive(ChannelHandlerContext ctx) { log.info('客戶端斷開連接,{}', ctx.channel().remoteAddress()); ctx.channel().close(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg){ RpcRequest rpcRequest = (RpcRequest) msg; log.info('接收到客戶端請求, 請求接口:{}, 請求方法:{}', rpcRequest.getClassName(), rpcRequest.getMethodName()); RpcResponse response = new RpcResponse(); response.setRequestId(rpcRequest.getRequestId()); Object result = null; try { result = this.handleRequest(rpcRequest); response.setResult(result); } catch (Exception e) { e.printStackTrace(); response.setSuccess(false); response.setErrorMessage(e.getMessage()); } log.info('服務器響應:{}', response); ctx.writeAndFlush(response); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { log.info('連接異常'); ctx.channel().close(); super.exceptionCaught(ctx, cause); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent){ IdleStateEvent event = (IdleStateEvent)evt; if (event.state()== IdleState.ALL_IDLE){ log.info('客戶端已超過60秒未讀寫數據, 關閉連接.{}',ctx.channel().remoteAddress()); ctx.channel().close(); } }else{ super.userEventTriggered(ctx,evt); } } private Object handleRequest(RpcRequest rpcRequest) throws Exception{ Object bean = rpcServices.get(rpcRequest.getClassName()); if(bean == null){ throw new RuntimeException('未找到對應的服務: ' + rpcRequest.getClassName()); } Method method = bean.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes()); method.setAccessible(true); return method.invoke(bean, rpcRequest.getParameters()); }}四、RPC客戶端

/** * RPC遠程調用的客戶端 */@Slf4j@Componentpublic class RpcClient { @Value('${rpc.remote.ip}') private String remoteIp; @Value('${rpc.remote.port}') private int port; private Bootstrap bootstrap; // 儲存調用結果 private final Map<String, SynchronousQueue<RpcResponse>> results = new ConcurrentHashMap<>(); public RpcClient(){ } @PostConstruct public void init(){ bootstrap = new Bootstrap().remoteAddress(remoteIp, port); NioEventLoopGroup worker = new NioEventLoopGroup(1); bootstrap.group(worker) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(new IdleStateHandler(0, 0, 10)); pipeline.addLast(new JsonEncoder()); pipeline.addLast(new JsonDecoder()); pipeline.addLast(new RpcClientInboundHandler(results)); } }); } public RpcResponse send(RpcRequest rpcRequest) { RpcResponse rpcResponse = null; rpcRequest.setRequestId(UUID.randomUUID().toString()); Channel channel = null; try { channel = bootstrap.connect().sync().channel(); log.info('連接建立, 發送請求:{}', rpcRequest); channel.writeAndFlush(rpcRequest); SynchronousQueue<RpcResponse> queue = new SynchronousQueue<>(); results.put(rpcRequest.getRequestId(), queue); // 阻塞等待獲取響應 rpcResponse = queue.take(); results.remove(rpcRequest.getRequestId()); } catch (InterruptedException e) { e.printStackTrace(); } finally { if(channel != null && channel.isActive()){ channel.close(); } } return rpcResponse; }}

RpcClientInboundHandler負責處理服務端的響應

@Slf4jpublic class RpcClientInboundHandler extends ChannelInboundHandlerAdapter { private Map<String, SynchronousQueue<RpcResponse>> results; public RpcClientInboundHandler(Map<String, SynchronousQueue<RpcResponse>> results){ this.results = results; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { RpcResponse rpcResponse = (RpcResponse) msg; log.info('收到服務器響應:{}', rpcResponse); if(!rpcResponse.isSuccess()){ throw new RuntimeException('調用結果異常,異常信息:' + rpcResponse.getErrorMessage()); } // 取出結果容器,將response放進queue中 SynchronousQueue<RpcResponse> queue = results.get(rpcResponse.getRequestId()); queue.put(rpcResponse); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent){ IdleStateEvent event = (IdleStateEvent)evt; if (event.state() == IdleState.ALL_IDLE){ log.info('發送心跳包'); RpcRequest request = new RpcRequest(); request.setMethodName('heartBeat'); ctx.channel().writeAndFlush(request); } }else{ super.userEventTriggered(ctx, evt); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){ log.info('異常:{}', cause.getMessage()); ctx.channel().close(); }}接口代理

為了使客戶端像調用本地方法一樣調用遠程服務,我們需要對接口進行動態代理。

代理類實現

@Componentpublic class RpcProxy implements InvocationHandler { @Autowired private RpcClient rpcClient; @Override public Object invoke(Object proxy, Method method, Object[] args){ RpcRequest rpcRequest = new RpcRequest(); rpcRequest.setClassName(method.getDeclaringClass().getName()); rpcRequest.setMethodName(method.getName()); rpcRequest.setParameters(args); rpcRequest.setParameterTypes(method.getParameterTypes()); RpcResponse rpcResponse = rpcClient.send(rpcRequest); return rpcResponse.getResult(); }}

實現FactoryBean接口,將生產動態代理類納入 Spring 容器管理。

public class RpcFactoryBean<T> implements FactoryBean<T> { private Class<T> interfaceClass; @Autowired private RpcProxy rpcProxy; public RpcFactoryBean(Class<T> interfaceClass){ this.interfaceClass = interfaceClass; } @Override public T getObject(){ return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, rpcProxy); } @Override public Class<?> getObjectType() { return interfaceClass; }}

自定義類路徑掃描器,掃描包下的RPC接口,動態生產代理類,納入 Spring 容器管理

public class RpcScanner extends ClassPathBeanDefinitionScanner { public RpcScanner(BeanDefinitionRegistry registry) { super(registry); } @Override protected Set<BeanDefinitionHolder> doScan(String... basePackages) { Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages); for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) { GenericBeanDefinition beanDefinition = (GenericBeanDefinition)beanDefinitionHolder.getBeanDefinition(); beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanDefinition.getBeanClassName()); beanDefinition.setBeanClassName(RpcFactoryBean.class.getName()); } return beanDefinitionHolders; } @Override protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException { return true; } @Override protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent(); }}

@Componentpublic class RpcBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { RpcScanner rpcScanner = new RpcScanner(registry); // 傳入RPC接口所在的包名 rpcScanner.scan('com.ygd.rpc.common.service'); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { }}

JSON編解碼器

/** * 將 RpcRequest 編碼成字節序列發送 * 消息格式: Length + Content * Length使用int存儲,標識消息體的長度 * * +--------+----------------+ * | Length | Content | * | 4字節 | Length個字節 | * +--------+----------------+ */public class JsonEncoder extends MessageToByteEncoder<RpcRequest> { @Override protected void encode(ChannelHandlerContext ctx, RpcRequest rpcRequest, ByteBuf out){ byte[] bytes = JSON.toJSONBytes(rpcRequest); // 將消息體的長度寫入消息頭部 out.writeInt(bytes.length); // 寫入消息體 out.writeBytes(bytes); }}

/** * 將響應消息解碼成 RpcResponse */public class JsonDecoder extends LengthFieldBasedFrameDecoder { public JsonDecoder(){ super(Integer.MAX_VALUE, 0, 4, 0, 4); } @Override protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf msg = (ByteBuf) super.decode(ctx, in); byte[] bytes = new byte[msg.readableBytes()]; msg.readBytes(bytes); RpcResponse rpcResponse = JSON.parseObject(bytes, RpcResponse.class); return rpcResponse; }}

測試我們編寫一個Controller進行測試

@RestController@RequestMapping('/hello')public class HelloController { @Autowired private HelloService helloService; @GetMapping('/sayHello') public String hello(String name){ return helloService.sayHello(name); }}

通過 PostMan調用 controller 接口 http://localhost:9998/hello/sayHello?name=小明

響應: Hello 小明

總結

本文實現了一個簡易的、具有基本概念的RPC,主要涉及的知識點如下:

網絡通信及通信協議的編碼、解碼 Java對象的序列化及反序列化 通信鏈路心跳檢測 Java反射 JDK動態代理

項目完整代碼詳見:https://github.com/yinguodong/netty-rpc

到此這篇關于Springboot整合Netty實現RPC服務器的示例代碼的文章就介紹到這了,更多相關Springboot RPC服務器內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 高光谱相机-近红外高光谱相机厂家-高光谱成像仪-SINESPEC 赛斯拜克 | ZHZ8耐压测试仪-上海胜绪电气有限公司 | 电机保护器-电动机综合保护器-上海硕吉电器有限公司 | 欧盟ce检测认证_reach检测报告_第三方检测中心-深圳市威腾检验技术有限公司 | 酸度计_PH计_特斯拉计-西安云仪 纯水电导率测定仪-万用气体检测仪-低钠测定仪-米沃奇科技(北京)有限公司www.milwaukeeinst.cn | 订做不锈钢_不锈钢定做加工厂_不锈钢非标定制-重庆侨峰金属加工厂 | 江门流水线|江门工作台|江门市伟涛行工业设备有限公司 | 电动高尔夫球车|电动观光车|电动巡逻车|电动越野车厂家-绿友机械集团股份有限公司 | 高效复合碳源-多核碳源生产厂家-污水处理反硝化菌种一长隆科技库巴鲁 | 展厅设计公司,展厅公司,展厅设计,展厅施工,展厅装修,企业展厅,展馆设计公司-深圳广州展厅设计公司 | 不锈钢管件(不锈钢弯头,不锈钢三通,不锈钢大小头),不锈钢法兰「厂家」-浙江志通管阀 | 开平机_纵剪机厂家_开平机生产厂家|诚信互赢-泰安瑞烨精工机械制造有限公司 | 英国雷迪地下管线探测仪-雷迪RD8100管线仪-多功能数字听漏仪-北京迪瑞进创科技有限公司 | 楼承板-开闭口楼承板-无锡海逵楼承板 | 盛源真空泵|空压机-浙江盛源空压机制造有限公司-【盛源官网】 | 自动检重秤-动态称重机-重量分选秤-苏州金钻称重设备系统开发有限公司 | 厦门网站建设_厦门网站设计_小程序开发_网站制作公司【麦格科技】 | 一体化预制泵站-一体化提升泵站-一体化泵站厂家-山东康威环保 | 河南膏药贴牌-膏药代加工-膏药oem厂家-洛阳今世康医药科技有限公司 | 棉柔巾代加工_洗脸巾oem_一次性毛巾_浴巾生产厂家-杭州禾壹卫品科技有限公司 | 环保袋,无纺布袋,无纺布打孔袋,保温袋,环保袋定制,环保袋厂家,环雅包装-十七年环保袋定制厂家 | 排烟防火阀-消防排烟风机-正压送风口-厂家-价格-哪家好-德州鑫港旺通风设备有限公司 | 空调风机,低噪声离心式通风机,不锈钢防爆风机,前倾皮带传动风机,后倾空调风机-山东捷风风机有限公司 | 工业硝酸钠,硝酸钠厂家-淄博「文海工贸」| 工程管道/塑料管材/pvc排水管/ppr给水管/pe双壁波纹管等品牌管材批发厂家-河南洁尔康建材 | 武汉创亿电气设备有限公司_电力检测设备生产厂家 | 煤矿支护网片_矿用勾花菱形网_缝管式_管缝式锚杆-邯郸市永年区志涛工矿配件有限公司 | 青岛空压机,青岛空压机维修/保养,青岛空压机销售/出租公司,青岛空压机厂家电话 | 长沙网站建设制作「网站优化推广」-网页设计公司-速马科技官网 | 辐射色度计-字符亮度测试-反射式膜厚仪-苏州瑞格谱光电科技有限公司 | 磷酸肌酸二钠盐,肌酐磷酰氯-沾化欣瑞康生物科技 | 渣油泵,KCB齿轮泵,不锈钢齿轮泵,重油泵,煤焦油泵,泊头市泰邦泵阀制造有限公司 | 健身器材-健身器材厂家专卖-上海七诚健身器材有限公司 | led太阳能路灯厂家价格_风光互补庭院灯_农村市政工程路灯-中山华可路灯品牌 | 圆盘鞋底注塑机_连帮鞋底成型注塑机-温州天钢机械有限公司 | 天津试验仪器-电液伺服万能材料试验机,恒温恒湿标准养护箱,水泥恒应力压力试验机-天津鑫高伟业科技有限公司 | 消泡剂-水处理消泡剂-涂料消泡剂-切削液消泡剂价格-东莞德丰消泡剂厂家 | 食药成分检测_调料配方还原_洗涤剂化学成分分析_饲料_百检信息科技有限公司 | 烟台金蝶财务软件,烟台网站建设,烟台网络推广 | 高清视频编码器,4K音视频编解码器,直播编码器,流媒体服务器,深圳海威视讯技术有限公司 | 杭州中策电线|中策电缆|中策电线|杭州中策电缆|杭州中策电缆永通集团有限公司 |