2-1 Start nacos to realize custom load balancing for service registration discovery

Brief description of memory points

1 nacos需要下载安装,手动启动
2 nacos通过配置文件中spring-name实现服务的注册
3 以下代码发现服务集群,通过服务实例ServiceInstance获取服务ip和端口
    List<ServiceInstance> instances = discoveryClient.getInstances("微服务名称");
4 这个步骤引入了一个自定义的负载均衡

Service management nacos installation and use

Install nacos

  • Download and unzip the installation package in zip format
下载地址:https://github.com/alibaba/nacos/releases
  • Start nacos in default standalone mode: startup.cmd -m standalone
  • Visit nacos: http://localhost:8848/nacos

Use nacos service registration function

  • 1 Add dependency
        <!--nacos服务注册发现-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
  • 2 Add configuration
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
  • 3 Add annotation to the main class @EnableDiscoveryClient
  • Verification: Check whether the registration is successful in the service list of the nacos console
  • Introduce the DiscoveryClient object in class 4 to achieve remote service information in the method
        // 根据微服务名称获取集群信息
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        // 随机数实现负载均衡,随机访问集群中某一个服务
        int random = new Random().nextInt(instances.size());
        ServiceInstance serviceInstance = instances.get(random);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();   
        // 拼接远程调用的服务地址
        String url = "http://" + host + ":" + port + "/product/" + pid;
        // 通过restTemplate远程调用对应服务
        Product product = restTemplate.getForObject(url, Product.class);
 = restTemplate.getForObject(url, Product.class);

Guess you like

Origin blog.csdn.net/weixin_45544465/article/details/105936533