RPC学习

RPC

远程过程调用
服务提供者 将服务提供到注册中心,消费者从注册中心获取需要i调用的服务,去进行调用

模块创建

在这里插入图片描述

消费者(Consumer)

在这里插入图片描述
** pom **

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>rpc01</artifactId><groupId>org.example</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>Consumer</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.example</groupId><artifactId>ProviderCommon</artifactId><version>1.0-SNAPSHOT</version></dependency><dependency><groupId>org.example</groupId><artifactId>ycrpc</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies></project>

** 代码**

package com.yc;import com.yc.common.Invocation;
import com.yc.protocol.HttpClient;
import com.yc.proxy.ProxyFactory;/*** @Author yc* @PackageName yeb* @Package com.yc* @Date 2023/9/5 17:05*/
public class Consumer {public static void main(String[] args) {
//        HelloService helloService = ProxyFactory.getProxy(HelloService.class);HelloService helloService = ProxyFactory.getProxy(HelloService.class);String result = helloService.sayHello("yc1111");System.out.println(result);}}
提供者(Provider)

在这里插入图片描述
** pom **

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>rpc01</artifactId><groupId>org.example</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>Provider</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.example</groupId><artifactId>ProviderCommon</artifactId><version>1.0-SNAPSHOT</version></dependency><dependency><groupId>org.example</groupId><artifactId>ycrpc</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies>
</project>

** 代码 **

package com.yc;import com.yc.common.URL;
import com.yc.protocol.HttpServer;
import com.yc.register.LocalRegister;
import com.yc.register.MapRemoteRegister;/*** @Author yc* @PackageName yeb* @Package com.yc* @Date 2023/9/5 17:11*/
public class Provider {public static void main(String[] args) {LocalRegister.regist(HelloService.class.getName(),"1.0",HelloServiceImpl.class);
//        LocalRegister.regist(HelloService.class.getName(),"1.0",HelloServiceImpl02.class);//注册中心注册,服务注册URL url = new URL("127.0.0.1",8181);MapRemoteRegister.regist(HelloService.class.getName(),url);HttpServer httpServer = new HttpServer();httpServer.start(url.getHostname(),url.getPort());}
}

在这里插入图片描述

ProviderCommon

在这里插入图片描述
在这里插入图片描述

** pom **

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>rpc01</artifactId><groupId>org.example</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>ProviderCommon</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties></project>
rpc

** pom **

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>rpc01</artifactId><groupId>org.example</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>ycrpc</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-core</artifactId><version>8.5.93</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-io</artifactId><version>1.3.2</version></dependency></dependencies></project>
启动tomcat
package com.yc.protocol;import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;/*** @Author yc* @PackageName yeb* @Package com.yc.protocol* @Date 2023/9/5 17:20*/
public class HttpServer {public void start(String hostName,Integer prot ){Tomcat tomcat = new Tomcat();Server server = tomcat.getServer();Service service = server.findService("Tomcat");Connector connector = new Connector();connector.setPort(prot);StandardEngine engine = new StandardEngine();engine.setDefaultHost(hostName);StandardHost host = new StandardHost();host.setName(hostName);String contextPath="";StandardContext context = new StandardContext();context.setPath(contextPath);context.addLifecycleListener(new Tomcat.FixContextListener());host.addChild(context);engine.addChild(host);service.setContainer(engine);service.addConnector(connector);tomcat.addServlet(contextPath,"dispatcher",new DisPatcherServlet());context.addServletMappingDecoded("/*","dispatcher");try {tomcat.start();tomcat.getServer().await();} catch (Exception e) {e.printStackTrace();}}}
DisPatcherServlet
package com.yc.protocol;import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import java.io.IOException;/*** @Author yc* @PackageName rpc01* @Package com.yc.protocol* @Date 2023/9/6 14:09*/
public class DisPatcherServlet extends HttpServlet {@Overridepublic void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {new HttpServerHandler().handler(req,res);}
}
HttpServerHandler
package com.yc.protocol;import com.yc.common.Invocation;
import com.yc.register.LocalRegister;
import org.apache.commons.io.IOUtils;import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;/*** @Author yc* @PackageName rpc01* @Package com.yc.protocol* @Date 2023/9/6 14:11*/
public class HttpServerHandler {public void handler(ServletRequest req, ServletResponse res) {// 处理请求 --》 接口、方法、方法参数try {Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();String interfaceName = invocation.getInterfaceName();Class classImpl = LocalRegister.get(interfaceName, "1.0");Method method = classImpl.getMethod(invocation.getMethodName(), invocation.getParameterTypes());String result = (String) method.invoke(classImpl.newInstance(), invocation.getParameters());IOUtils.write(result, res.getOutputStream());} catch (Exception e) {e.printStackTrace();}}
}
Invocation(调用对象)
package com.yc.common;import java.io.Serializable;/*** @Author yc* @PackageName rpc01* @Package com.yc.common* @Date 2023/9/6 14:13*/
public class Invocation implements Serializable {private String interfaceName; //接口名private String methodName; //方法名private Class[] parameterTypes;//参数类型private Object[] parameters;//参数public Invocation(String interfaceName, String methodName,  Class[] parameterTypes, Object[] parameters) {this.interfaceName = interfaceName;this.methodName = methodName;this.parameterTypes = parameterTypes;this.parameters = parameters;}public String getInterfaceName() {return interfaceName;}public void setInterfaceName(String interfaceName) {this.interfaceName = interfaceName;}public String getMethodName() {return methodName;}public void setMethodName(String methodName) {this.methodName = methodName;}public Class[] getParameterTypes() {return parameterTypes;}public void setParameterTypes(Class[] parameterTypes) {this.parameterTypes = parameterTypes;}public Object[] getParameters() {return parameters;}public void setParameters(Object[] parameters) {this.parameters = parameters;}
}
LocalRegister(本地注册)
package com.yc.register;import java.util.HashMap;
import java.util.Map;/*** @Author yc* @PackageName rpc01* @Package com.yc.register* @Date 2023/9/6 14:19*/
public class LocalRegister {private static Map<String ,Class> map = new HashMap<>();public static void regist(String interfaceName ,String version ,Class implClass){map.put(interfaceName+version,implClass);}public static Class get(String interfaceName ,String version){return map.get(interfaceName+version);}
}
URL对象
package com.yc.common;import java.io.Serializable;/*** @Author yc* @PackageName rpc01* @Package com.yc.common* @Date 2023/9/6 15:11*/
public class URL implements Serializable {private String hostname;private Integer port;public URL(String hostname, Integer port) {this.hostname = hostname;this.port = port;}public String getHostname() {return hostname;}public void setHostname(String hostname) {this.hostname = hostname;}public Integer getPort() {return port;}public void setPort(Integer port) {this.port = port;}
}
发送http请求
package com.yc.protocol;import com.yc.common.Invocation;
import org.apache.commons.io.IOUtils;import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;/*** @Author yc* @PackageName rpc01* @Package com.yc.protocol* @Date 2023/9/6 14:39*/
public class HttpClient {public String send(String hostname, Integer port, Invocation invocation) throws Exception {try {URL url = new URL("http", hostname, port, "/");HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.setRequestMethod("POST");httpURLConnection.setDoOutput(true);//配置OutputStream outputStream = httpURLConnection.getOutputStream();ObjectOutputStream oss = new ObjectOutputStream(outputStream);oss.writeObject(invocation);oss.flush();oss.close();InputStream inputStream = httpURLConnection.getInputStream();String result = IOUtils.toString(inputStream);return result;} catch (Exception e) {e.printStackTrace();throw e;}}
}
ProxyFactory(代理对象)
package com.yc.proxy;import com.yc.common.Invocation;
import com.yc.common.URL;
import com.yc.loadbalance.Loadbalance;
import com.yc.protocol.HttpClient;
import com.yc.register.MapRemoteRegister;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;/*** @Author 杨超* @PackageName rpc01* @Package com.yc.proxy* @Date 2023/9/6 15:03*/
public class ProxyFactory {public static <T> T getProxy(Class interfaceClass) {Object proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                String mock = System.getProperty("mock");
//                if (mock != null && mock.startsWith("return:")) {
//                    String result = mock.replace("return:", "");
//                    return result;
//                }Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(),method.getParameterTypes(), args);HttpClient httpClient = new HttpClient();//服务发现List<URL> list = MapRemoteRegister.get(interfaceClass.getName());//服务调用String result = null;List<URL> invokedUrls = new ArrayList<>();int max = 5;while (max > 0) {//负载均衡list.remove(invokedUrls);URL url = Loadbalance.random(list);invokedUrls.add(url);try {result = httpClient.send(url.getHostname(), url.getPort(), invocation);return result;} catch (Exception e) {e.printStackTrace();if (max-- == 0) {continue;}// error-callback = com.yc.helloServiceErrorCallback//容错return "报错了";}}return result;}});return (T) proxyInstance;}}
MapRemoteRegister (模拟远程注册中心)
package com.yc.register;import com.yc.common.URL;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @Author yc* @PackageName rpc01* @Package com.yc.register* @Date 2023/9/6 15:12*/
public class MapRemoteRegister {private static Map<String, List<URL>> map = new HashMap<>();public static void regist(String interfaceName, URL url) {List<URL> list = map.get(interfaceName);if (list == null) {list = new ArrayList<>();}list.add(url);map.put(interfaceName, list);saveFile();}public static List<URL> get(String interfaceName) {map = getFile();return map.get(interfaceName);}private static void saveFile() {try {FileOutputStream fileOutputStream = new FileOutputStream("D:\\yc\\Java\\idea\\idea-work\\project\\rpc01\\temp.txt");ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);objectOutputStream.writeObject(map);} catch (Exception e) {e.printStackTrace();}}private static Map<String, List<URL>> getFile() {try {FileInputStream fileInputStream = new FileInputStream("D:\\yc\\Java\\idea\\idea-work\\project\\rpc01\\temp.txt");ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);return (Map<String, List<URL>>) objectInputStream.readObject();} catch (Exception e) {e.printStackTrace();}return null;}}
简单的负载均衡
package com.yc.loadbalance;import com.yc.common.URL;import javax.annotation.Resource;
import java.util.List;
import java.util.Random;/*** @Author 杨超* @PackageName rpc01* @Package com.yc.loadbalance* @Date 2023/9/6 15:19*/
public class Loadbalance {public static URL random(List<URL> urls){Random random = new Random();int i = random.nextInt(urls.size());return urls.get(i);}
}

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

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

相关文章

【萤火虫系列教程】2/5-Adobe Firefly 文字​生成​图像

文字​生成​图像 登录账号后&#xff0c;在主页点击文字生成图像的【生成】按钮&#xff0c;进入到文字生成图像 查看图像 在文字生成图像页面&#xff0c;可以看到别人生成的图像。 点击某个图像&#xff0c;就可以进入图像详情&#xff0c;可以看到文字描述。 生成图像 我…

Socket与TCP的关系

前言 相信大家对于TCP已经非常熟悉了&#xff0c;学习过计算机网络的同学对于它的连接和断开流程应该已经烂熟于心了吧。 那么Socket是什么&#xff1f; Socket是应用层与TCP/IP协议簇通信的中间软件抽象层&#xff0c;它是一组接口。在设计模式中&#xff0c;Socket其实就是…

python 写自动点击爬取数据

今天来点不一样的&#xff01;哥们 提示&#xff1a; 这里只是用于自己学习的 &#xff0c;请勿用违法地方 效果图 会进行点击下一页 进行抓取 需要其他操作也可以自己写 文章目录 今天来点不一样的&#xff01;哥们前言一、上代码&#xff1f;总结 前言 爬虫是指通过编程自动…

基于Java实现全功能电子商城

&#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩项目推荐订阅&#x1f447;&#x1f3fb; 不然下次找不到哟 基于SpringBoot的旅游网站 基于SpringBoot的MusiQ音乐网站 感兴趣的可以先收藏起来&#xff0c;还有大家在毕设选题&#xff0c;项目以及…

嵌入式培训机构四个月实训课程笔记(完整版)-Linux系统编程第四天-Linux管道练习题(物联技术666)

更多配套资料CSDN地址:点赞+关注,功德无量。更多配套资料,欢迎私信。 物联技术666_嵌入式C语言开发,嵌入式硬件,嵌入式培训笔记-CSDN博客物联技术666擅长嵌入式C语言开发,嵌入式硬件,嵌入式培训笔记,等方面的知识,物联技术666关注机器学习,arm开发,物联网,嵌入式硬件,单片机…

基础面试题整理2

1.抽象类与接口区别 语法&#xff1a; 抽象类用abstract定义&#xff1b;接口用interface定义抽象类被子类继承extends&#xff08;不可用final修饰&#xff09;&#xff1b;接口被类实现implements抽象类的属性访问无限制,方法不可用private修饰&#xff1b;接口中的方法只能…

性能分析与调优: Linux 使用ELRepo升级CentOS内核

目录 一、实验 1.环境 2.agent 服务器使用ELRepo升级CentOS内核 二、问题 1. RHEL-7, SL-7 或者 CentOS-7系统如何安装ELRepo 2.RHEL-8或者RHEL-9系统如何安装ELRepo 一、实验 1.环境 &#xff08;1&#xff09;主机 表1-1 主机 主机架构组件IP备注prometheus 监测 系…

【uniapp】APP打包上架应用商-注意事项

初雪云-uniapp启动图自定义生成&#xff08;支持一键生成storyboard&#xff09; 一、修改App端上传图片/视频 uni.uploadFile let thatthis; uni.chooseImage({count: 1,sourceType: [camera,album],sizeType: [compressed, original],success: rey > {uni.showLoading({ t…

欢乐钓鱼^^

欢迎来到程序小院 欢乐钓鱼 玩法&#xff1a;点击鼠标左键左右晃动的鱼钩&#xff0c;下方左右移动的鱼对准鱼的方向即可进行钓鱼&#xff0c; 不同的鱼不同的分数&#xff0c;快去钓鱼吧^^开始游戏https://www.ormcc.com/play/gameStart/241 html <div id"gamediv&qu…

【深度学习:Embeddings 】机器学习中Embeddings的完整指南

人工智能嵌入提供了生成优质训练数据的潜力&#xff0c;提高了数据质量并最大限度地减少了手动标记要求。通过将输入数据转换为机器可读的格式&#xff0c;企业可以利用人工智能技术来转变工作流程、简化流程并优化性能。 机器学习是一种强大的工具&#xff0c;有潜力改变我们…

时钟的实现(MFC)

文章目录 1.预备知识1.日期和时间类1.概述2.构造3.CTime类主要成员函数3.CTimeSpan类主要成员函数 2.计时器1.创建计时器2.销毁计时器 3.位图类1.构造2.初始化3.属性4.操作 2.实验目的3.实验内容4.代码实现1.准备工作2.基类CClockBaseClockBase.hClockBase.cpp 3.时钟背景类CCl…

【软件测试】学习笔记-测试覆盖率

测试覆盖率通常被用来衡量测试的充分性和完整性&#xff0c;从广义的角度来讲&#xff0c;测试覆盖率主要分为两大类&#xff0c;一类是面向项目的需求覆盖率&#xff0c;另一类是更偏向技术的代码覆盖率。 需求覆盖率 需求覆盖率是指测试对需求的覆盖程度&#xff0c;通常的做…