Spring Cloud Alibaba Study Notes (2)---Nacos Discovery--Service Governance

Nacos Discovery – Service Governance

1.1 Introduction to service governance


Let’s think about a question first

Through the operations in the previous chapter, we can already implement calls between microservices. However, we have hard-coded the service provider's network address (ip, port) into the code. This approach has many problems: once the service provider address changes, the code needs to be modified manually. Once there are multiple service providers, it cannot be implemented. Once the load balancing function has more and more services, it is difficult to manually maintain the calling relationship. How to solve the problem? At this time, it is necessary to dynamically implement service governance through the registration center.

What is service governance?

Service governance is the core and most basic module in the microservice architecture. Used to realize automated registration and discovery of each microservice.
Service registration: In the service governance framework, a registration center will be built, and each service unit will register the detailed information of the services it provides with the registration center. A list of services is formed in the registration center. The service registration center needs to monitor whether the services in the list are available in a heartbeat manner. If not, the unavailable services need to be removed from the service list.

Service discovery: The service calling direction consults the service registration center and obtains the instance list of all services to achieve access to specific service instances.

Insert image description here

Through the call graph above, you will find that in addition to microservices, there is another component called the service registration center. It is a very important component of the microservice architecture and mainly plays the role of a coordinator in the microservice architecture. The registration center generally includes the following functions:

  1. Service discovery: Service registration: saves the information of service providers and service callers. Service subscription: service callers subscribe to service provider information, and the registration center pushes provider information to subscribers.
  2. Service configuration: Configuration subscription: Service providers and service callers subscribe to microservice-related configuration configuration delivery: Actively push configurations to service providers and service callers
  3. Service health detection detects the health of the service provider. If an abnormality is found, the service is removed.

Common registration centers

Zookeeper is a distributed service framework and a sub-project of Apache Hadoop. It is mainly used to solve some data management problems often encountered in distributed applications, such as: unified naming service, status synchronization service, cluster management, distributed Management of application configuration items, etc.

Eureka Eureka is an important component in Springcloud Netflix. Its main function is service registration and discovery. But now it is closed source Consul

Consul is an open source tool developed based on the GO language. It mainly provides service registration, service discovery and configuration management functions for distributed and service-oriented systems. Consul's functions are very practical, including: service registration/discovery, health check, Key/Value storage, multi-data center and distributed consistency guarantee and other features. Consul itself is just a binary executable file, so installation and deployment are very simple. You only need to download it from the official website and execute the corresponding startup script.

Nacos Nacos is a dynamic service discovery, configuration management and service management platform that makes it easier to build cloud native applications. It is one of the Spring Cloud Alibaba
components and is responsible for service registration discovery and service configuration. You can think of nacos=eureka+config.

3.2 Introduction

Nacos is dedicated to helping you discover, configure and manage microservices. Nacos
provides a simple and easy-to-use feature set to help you quickly implement dynamic service discovery, service configuration, service metadata and traffic management.

As can be seen from the above introduction, nacos functions as a registration center to manage each registered microservice.

3.3 Getting started with nacos practice


Next, we will add nacos to the existing environment and register our two microservices.

3.3.1 Set up nacos environment

Step 1: Install nacos
download address:

https://github.com/alibaba/nacos/releases/download/1.4.2/nacos-server-1.4.2.zip

Step 2: Start nacos
Insert image description here

Step 3: Visit nacos

Open the browser and enter http://localhost:8848/nacos to access the service. The default password is nacos/nacos
Insert image description here
Insert image description here

3.3.2 Register the product microservice to nacos.
Next, modify the code of the shop-product module and register it to the nacos service.
1. Add nacos dependencies in pom.xml

<!--nacos客户端-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2 Add the @EnableDiscoveryClient annotation to the main class

@SpringBootApplication
@MapperScan(basePackages = "com.gby.dao")
@EnableDiscoveryClient
public class ProductApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(ProductApplication.class, args);
    }
}

4 Start the service
Insert image description here
3.3.3 Register the order microservice to nacos
Next, modify the code of the shop-order module and register it to the nacos service
1. Add dependencies to pom.xml

<!--nacos客户端-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2 Add annotations to the main class

@SpringBootApplication
@MapperScan(basePackages = "com.gby.dao")
@EnableDiscoveryClient
public class OrderApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(OrderApplication.class,args);
    }

    @Bean
    public RestTemplate restTemplate(){
    
    
        return new RestTemplate();
    }
}

3 Add the address of the nacos service in application.yml

server:
  port: 8071
spring:
  application:
    name: service-order
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
mybatis:
  mapper-locations: classpath:com/gby/dao/*Mapper.xml
  type-aliases-package: com.gby.entity
logging:
  level:
    com:
      gby:
        dao: debug

4 Modify OrderController to implement microservice calls

/**
 * 作者: Sky
 *
 * @Description:
 */
@RestController
public class OrderController {
    
    
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    DiscoveryClient discoveryClient;

    @RequestMapping("order/save/{pid}")
    public JsonResult saveOrderByPid(@PathVariable("pid") Integer pid) {
    
    
        //客户下订单,这个时候要调用商品微服务查询商品信息
//        String url = "http://localhost:8061/product/" + pid;

        //根据服务名称获取服务列表
        List<ServiceInstance> instances=discoveryClient.getInstances("service-product");
        //获取第一个服务
        ServiceInstance serviceProduct = instances.get(0);
        //获取地址和端口
        String hostAndPortUrl="http://"+serviceProduct.getHost()+":"+serviceProduct.getPort();
        //客户下订单
        String url=hostAndPortUrl+"/product/"+pid;

        //返回值类型(因为JsonResult的Data是泛型类型属性)
        ParameterizedTypeReference<JsonResult<Product>> typeReference =
                new ParameterizedTypeReference<JsonResult<Product>>() {
    
    
                };
        //发出请求get请求,请求参数为空
        ResponseEntity<JsonResult<Product>> exchange =
                restTemplate.exchange(url, HttpMethod.GET, null, typeReference);
        //返回值的body属性是请求api的返回数据
        Product product = exchange.getBody().getData();

        //创建Order对象
        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(product.getPid());
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        //保存order对象
        orderService.save(order);

        return new JsonResult(0, "", order);
    }
}

DiscoveryClient is specifically responsible for service registration and discovery. We can use it to obtain all services registered in the registration center.
5 Start the service, observe whether there are registered order microservices in the nacos control panel, and then verify the call by accessing the consumer service whether succeed
Insert image description here

test
input

http://localhost:8071/order/save/1

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_48434899/article/details/127024249