In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to use Springboot and Netty to achieve rpc". In daily operation, I believe many people have doubts about how to use Springboot and Netty to achieve rpc. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use Springboot and Netty to achieve rpc". Next, please follow the editor to study!
Springboot, Netty, dynamic proxy (reflection), reflection
The overall structure of the project is as follows:
1. Introduce related dependencies in the parent project Org.springframework.boot spring-boot-starter-web 2.3.2.RELEASE io.netty netty-all 4.1.48.Final com.alibaba fastjson 1.2.58 Org.slf4j slf4j-log4j12 2.0.0-alpha1 2. The overall structure of the service provision module is as follows:
Here we focus on two message body classes, RequestModel and ResponseModel.
@ Data@AllArgsConstructorpublic class RequestModel {private String requestId; private String serviceName; private String methodName; private Class [] paramTypes; private Object [] paramValues;} @ Data@AllArgsConstructorpublic class ResponseModel {private String responseId; private String serviceName; private String methodName; private String code; private String data;}
It is used for the data transmission between the server and the client, and then pays attention to the decoding processing of channelRead0 () message in ServerChannelInboundHandler.
Override protected void channelRead0 (ChannelHandlerContext ctx, String msg) {StringBuilder sb = null; RequestModel result = null; try {/ / message parsing processing sb = new StringBuilder (); result = JSON.parseObject (msg, RequestModel.class); requestId = result.getRequestId (); String serviceName = result.getServiceName (); String methodName = result.getMethodName () Class [] paramType = result.getParamTypes (); Object [] paramValue = result.getParamValues (); System.out.println (serviceName + "" + methodName); String substring = serviceName.substring (serviceName.lastIndexOf (".") + 1); String s = substring.substring (0,1). ToLowerCase () + substring.substring (1); Object serviceObject = applicationContext.getBean (s) Method method = Class.forName (serviceName) .getMethod (methodName, paramType); Object returnValue = method.invoke (serviceObject, paramValue); ResponseModel responseModel = new ResponseModel (requestId,serviceName,methodName, "200", JSON.toJSONString (returnValue)); sb.append (JSON.toJSONString (responseModel)); sb.append ("\ n "); System.out.println (sb.toString ()) Ctx.writeAndFlush (sb);} catch (Exception e) {ResponseModel responseModel = new ResponseModel (requestId, "500", e.getMessage ()); String errorCode = JSON.toJSONString (responseModel) + "\ n"; log.error (errorCode); ctx.writeAndFlush (errorCode); log.error ("message parsing failed:" + e.getMessage ()) }}
The module code for the client is as follows
The focus here is on the handling of the channelRead0 () method in the ClientHandler class
@ Override protected void channelRead0 (ChannelHandlerContext ctx, String msg) {System.out.println ("receive server message:" + msg); ResponseModel responseModel = JSON.parseObject (msg,ResponseModel.class); String responseId = responseModel.getResponseId (); Promise promise = LocalPromise.promiseMap.remove (responseId); if (promise! = null) {String code = responseModel.getCode () If (code.equals) {promise.setSuccess (responseModel.getData ());} else {promise.setFailure (new RuntimeException (responseModel.getData ();}
And the processing of getting services in the AppStart class
Private T getProxyService (Class serviceClass) {Object service = Proxy.newProxyInstance (serviceClass.getClassLoader (), new Class [] {serviceClass}, new InvocationHandler () {@ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {Channel channel = NettyClient.getChannel (host, port) RequestModel requestModel = new RequestModel ("100001", method.getDeclaringClass (). GetName (), method.getName (), method.getParameterTypes (), args); channel.writeAndFlush (JSON.toJSONString (requestModel) + "\ n"); Promise promise = new DefaultPromise (channel.eventLoop ()); LocalPromise.promiseMap.put (requestModel.getRequestId (), promise) System.out.println (LocalPromise.promiseMap+ ">"); promise.await (); if (promise.isSuccess ()) {Class returnType = method.getReturnType (); return JSON.toJavaObject (JSON.parseObject (promise.getNow () + "), returnType) } else {System.out.println (promise.cause ()); return promise.cause ();}); return (T) service;}
Test results:
At this point, the study on "how to use Springboot and Netty to achieve rpc" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.