当前位置:网站首页>Custom RPC project - frequently asked questions and explanations (Registration Center)
Custom RPC project - frequently asked questions and explanations (Registration Center)
2022-07-06 13:36:00 【Li bohuan】
Take the book back , Customize RPC project —— Common problems and detailed explanations (Netty piece )_ Li bohuan's blog -CSDN Blog , Let's talk about it later , This RPC Frequently asked questions about the project :
Project address :https://blog.csdn.net/qq_40856284/category_10138756.html
Four 、 Registry Center
1. Why use a registry ?
Before using and learning the registry , First of all, we need to be clear , Why use a registry ? With the development of Internet architecture ( Single application architecture ==> Vertical application architecture ==> Distributed architecture ==>SOA framework ==> Microservice architecture ), More and more services , The dependencies between services are also more complex , It is difficult to directly call services , The implementation process is also more complex , And to improve the reliability of the service , The registration center came into being .
The concept of registry plays an important role in the architecture of service-oriented design , Whether in SOA Architecture is still in the microservice architecture , The role of the registry can be summed up in a word Storage and scheduling services , Implement services and registries , Services and communication between services . The registry can be said to be in the microservice architecture ” Mail list “, It records the mapping relationship between service and service address . In a distributed architecture , The service will register here , When a service needs to call another service , Just find the address of the service here , To call . Here are some common registry features :
2. Why use Nacos As the registration center of the project ?
Nacos Alibaba is an open-source dynamic service discovery that is easier to build cloud native applications 、 Configuration management and service management platform .( Configuration center 、 Registry Center )
Look at the watch above ,nacos The most comprehensive features supported . Open the box , Simple to use , I haven't found a big hole yet ,nacos More features , The community is more active . If you are interviewing Ali , Direct said Because it was developed by Ali , Stand the test of various applications in large factories , There must be no problem .
3. Common registry differences ?
See this article . Microservices : Registry Center ZooKeeper、Eureka、Consul 、Nacos contrast _ Qiyan's blog -CSDN Blog _consul nacos
4. What are the minimum conditions for a registration center ?
Service registration interface : The service provider completes the service registration by calling the service registration interface .
Service de registration interface : The service provider calls the service deregistration interface to complete the service deregistration .
Heartbeat reporting interface : The service provider completes the node survival status reporting by calling the heartbeat reporting interface .
Service subscription interface : The service consumer completes the service subscription by calling the service subscription interface , Get the list of available service provider nodes .
Service change query interface : The service consumer changes the query interface by calling the service , Get the latest list of available service nodes .
Service query interface : Query the service information currently registered in the registry .
Service modification interface : Modify the information of a service in the registry .
5. The registration center is a single machine or a cluster , What if one of them hangs up ? Uniformity , How to guarantee reliability ?
In my project , It is a stand-alone version nacos.nacos You can see the following blog for the cluster deployment scheme of
Then we need to realize the registration center from stand-alone version to distributed cluster , There are several key problems to be solved :
The relationship between cluster members and member discovery problems
Data replication and consistency among cluster members
Data replication mechanism and data partition strategy
Specific solutions can be seen : Design principle and implementation of distributed cluster in microservice registry Golang Realization (136.la)
6. What do distributed data consistency protocols know ?
7.CAP Theoretical understanding ?
CAP Theory is the most important theory in distributed architecture
- C Uniformity : For each read operation of the client , Or read the latest data , Either the read failed . let me put it another way , Consistency is from the perspective of distributed system , A commitment to clients accessing the system : Or I'll return you an error , Or I'll return you the absolutely consistent latest data , It's not hard to see. , It emphasizes that the data is correct .
- A Usability : Any client request can get response data , There are no response errors . let me put it another way , Availability is from the perspective of distributed systems , Another commitment to customers accessing the system : I will definitely return the data to you , It won't return you an error , But the data is not guaranteed to be up-to-date , The emphasis is not to make mistakes .
- P Zone tolerance : Because the distributed system communicates through the network , The network is unreliable . When any number of messages are lost or arrive late , The system will continue to provide services , Will not hang up . let me put it another way , Partition tolerance is from the perspective of distributed system , Another commitment to the client accessing the system : I'll keep running , No matter what kind of data synchronization problem occurs inside me , The emphasis is not to hang up .
All distributed systems must have partition tolerance , Because partition tolerance is the basic condition of distributed systems , But there can only be one consistency and availability , It's just CP perhaps AP The system of , There is no such thing as CAP All established systems . Because in order to meet the consistency, the system must copy the data to each micro service , This leads to a great performance consumption , There will be usability problems , So you can't have both .
8. Any request ( Traffic ) Will you call the registration center when you come here ?
First meeting , When Ask the registry after , Save the service list locally ( Consumer memory ), Convenient for future use .
9. If it's how you design one nacos ,rpc How to call .
【Nacos】Nacos Principle analysis _Coinker The blog of -CSDN Blog _nacos Principle
10.raft Understand ?
Nacos Of Raft Algorithm _ Overtime crazy blog -CSDN Blog _nacos raft
11. In the project nacos Specific use of the registry
Introduce dependencies
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>1.3.0</version>
</dependency>
First, define an interface ,ServiceRegistry As a remote registry (Nacos) Use
public interface ServiceRegistry {
/**
* Register a service into the registry
*
* @param serviceName The service name
* @param inetSocketAddress The address where the service is provided
*/
void register(String serviceName, InetSocketAddress inetSocketAddress);
}
register The method is to put the name of the service ( The interface name ) And address are registered in the service registration center , The interface has , We can write implementation classes , We achieve one Nacos As the implementation class of the registry :NacosServiceRegistry, We can also use ZooKeeper As a registry , Just implement the interface .
public class NacosServiceRegistry implements ServiceRegistry {
private static final Logger logger = LoggerFactory.getLogger(NacosServiceRegistry.class);
@Override
public void register(String serviceName, InetSocketAddress inetSocketAddress) {
try {
NacosUtil.registerService(serviceName, inetSocketAddress);
} catch (NacosException e) {
logger.error(" An error occurred while registering the service :", e);
throw new RpcException(RpcError.REGISTER_SERVICE_FAILED);
}
}
}
Here is a Nacos The utility class registerService Method to register the service ,NacosUtil Class is defined as follows , Three methods are mainly implemented , Registration service , Get all instances of the service and log out of the service .
public class NacosUtil {
private static final Logger logger = LoggerFactory.getLogger(NacosUtil.class);
private static final NamingService namingService;
private static final Set<String> serviceNames = new HashSet<>();
private static InetSocketAddress address;
private static final String SERVER_ADDR = "127.0.0.1:8848";
static {
namingService = getNacosNamingService();
}
public static NamingService getNacosNamingService() {
try {
return NamingFactory.createNamingService(SERVER_ADDR);
} catch (NacosException e) {
logger.error(" Connect to Nacos Errors occur from time to time : ", e);
throw new RpcException(RpcError.FAILED_TO_CONNECT_TO_SERVICE_REGISTRY);
}
}
public static void registerService(String serviceName, InetSocketAddress address) throws NacosException {
namingService.registerInstance(serviceName, address.getHostName(), address.getPort());
NacosUtil.address = address;
serviceNames.add(serviceName);
}
public static List<Instance> getAllInstance(String serviceName) throws NacosException {
return namingService.getAllInstances(serviceName);
}
public static void clearRegistry() {
if(!serviceNames.isEmpty() && address != null) {
String host = address.getHostName();
int port = address.getPort();
Iterator<String> iterator = serviceNames.iterator();
while(iterator.hasNext()) {
String serviceName = iterator.next();
try {
namingService.deregisterInstance(serviceName, host, port);
} catch (NacosException e) {
logger.error(" Log out of service {} Failure ", serviceName, e);
}
}
}
}
}
Nacos It's easy to use , adopt NamingFactory establish NamingService Connect Nacos, The connection process is written in a static code block , Automatically connect when the class is loaded .namingService It provides two very convenient interfaces ,registerInstance and getAllInstances Method , The former can be directed to Nacos Registration service , The latter can get a list of all providers that provide a service . So the two methods of the interface only need to be wrapped .
stay NacosUtil In which we pass getAllInstance After getting the list of all providers of a service , You have to choose one , This involves the load balancing strategy , Here we choose the first 0 individual , Later, we will explain load balancing in detail .
Next , We modify RpcServer Interface , Add a new method publishService, Used to direct to Nacos Registration service :
<T> void publishService(Object service, Class<T> serviceClass);
Then you just need to implement this method , With NettyServer For example ,NettyServer You need to create a ServiceRegistry 了 :
public NettyServer(String host, int port) {
this.host = host;
this.port = port;
serviceRegistry = new NacosServiceRegistry();
serviceProvider = new ServiceProviderImpl();
}
public <T> void publishService(Object service, Class<T> serviceClass) {
if(serializer == null) {
logger.error(" Serializer not set ");
throw new RpcException(RpcError.SERIALIZER_NOT_FOUND);
}
serviceProvider.addServiceProvider(service);
serviceRegistry.register(serviceClass.getCanonicalName(), new InetSocketAddress(host, port));
}
there serviceProvider Is the instance object of the local saved service class ,publishService The service needs to be saved in the local registry , Also register to Nacos On .
Finally, there is the service discovery part , Let's summarize it later with load balancing ! I think it's useful for everyone , You can give bloggers a compliment ~
边栏推荐
- ArrayList的自动扩容机制实现原理
- 6. Function recursion
- Counter attack of flour dregs: redis series 52 questions, 30000 words + 80 pictures in detail.
- String abc = new String(“abc“),到底创建了几个对象
- hashCode()与equals()之间的关系
- 12 excel charts and arrays
- List set map queue deque stack
- System design learning (I) design pastebin com (or Bit.ly)
- [中国近代史] 第九章测验
- CorelDRAW plug-in -- GMS plug-in development -- Introduction to VBA -- GMS plug-in installation -- Security -- macro Manager -- CDR plug-in (I)
猜你喜欢
随机推荐
【九阳神功】2016复旦大学应用统计真题+解析
2.初识C语言(2)
View UI Plus 发布 1.1.0 版本,支持 SSR、支持 Nuxt、增加 TS 声明文件
西安电子科技大学22学年上学期《基础实验》试题及答案
Implement queue with stack
一段用蜂鸣器编的音乐(成都)
[the Nine Yang Manual] 2018 Fudan University Applied Statistics real problem + analysis
System design learning (III) design Amazon's sales rank by category feature
【九阳神功】2021复旦大学应用统计真题+解析
Rich Shenzhen people and renting Shenzhen people
Application architecture of large live broadcast platform
5.MSDN的下载和使用
View UI plus released version 1.2.0 and added image, skeleton and typography components
Questions and answers of "Fundamentals of RF circuits" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology
The latest tank battle 2022 - Notes on the whole development -2
Mortal immortal cultivation pointer-2
受检异常和非受检异常的区别和理解
抽象类和接口的区别
魏牌:产品叫好声一片,但为何销量还是受挫
9. Pointer (upper)