SpringCloudAlibaba microservice distributed architecture

1. Introduction to Spring Cloud Alibaba

pending upgrade

2. Overview of Nacos

1. What is nacos?

A dynamic service discovery , configuration management and service management platform that is         easier to build cloud-native applications , which is equivalent to the combination of registration center + configuration center, equivalent to Eureka+Config+Bus.

2. What can I do?

  • Replace Eureka as a service registry
  • Replace config as service configuration center 

3. Where to go?      

        Official website download: click to visit

 Here I downloaded the Windows version. After the download is complete, go to the bin directory of the folder to start nacos:

4. How to run the access?

We have preliminarily installed Nacos above, and we need to pay attention to the following issues when starting:

  • If we start startup.cmd directly through cmd, we find that it can be started but an error will be reported, because the default startup mode of nacos is cluster, so we need to change to stand-alone mode  startup.cmd -m standalone

  • At this time, it can be started normally, but we use Nacos to engage in microservices, why do we need to engage in stand-alone?
    Nacos is started in cluster mode by default, but for beginners, it may be the first installation without a cluster environment that requires some configuration. In the entry stage, we still use a single machine as the main practice.
  • Configure cluster mode startup

        Copy the cluster.conf.example file and remove the .example suffix, then enter the file to modify, add a port, and then start it through startup.cmd .

  • Visit localhost:8848/nacos

 3. Nacos Service Registration Center

Official document: Click to view

1. Service provider module (building moudle, changing pom, writing yml, main startup, business class)

(1) Create moudle: cloudalibaba-provider-payment9001

(2) Change pom (add dependencies):

  • Parent pom (common):
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-dependencies</artifactId>
    <version>2.1.0.RELEASE</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>
  • Child pom:
<!--SpringCloud ailibaba nacos -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

(3) Write the configuration file application.yml

server:
  port: 9001

spring:
  application:
    name: nacos-payment-provider #注册服务名称
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址
#打开全部监控端点
management:
  endpoints:
    web:
      exposure:
        include: '*'

(4) The main startup class PaymentMain9001.java

@EnableDiscoveryClient  //开启服务提供者或消费者,客户端的支持,用来注册服务或连接到注册中心
@SpringBootApplication  //主启动
public class PaymentMain9001
{
    public static void main(String[] args) {
            SpringApplication.run(PaymentMain9001.class, args);
    }
}

(5) Write the business class PaymentController.java

@RestController
public class PaymentController
{
    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/payment/nacos/{id}")
    public String getPayment(@PathVariable("id") Integer id)
    {
        return "nacos registry, serverPort: "+ serverPort+"\t id"+id;
    }
}

(6) Test

  • Start Nacos and cloudaliba-provider-payment9001 module.
  • Visit http://localhost:9001/payment/nacos/1
  • Discover the services registered in the Nacos service registry in the service list: nacos-payment-provider

 2. Service provider module (copy, test the load balancing function of nacos)

(1) Copy the code of the 9001 module and change the file name and port number, but repeat it;

(2) There are two healthy instances under the same service name.

insert image description here

 3. Service consumers (building moudle, changing pom, writing yml, main startup, business class)

(1) Create moudle: cloudalibaba-consumer-nacos-order83

(2) Change pom (add dependencies):

<!--SpringCloud ailibaba nacos -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

(3) Write the configuration file application.yml

server:
  port: 83


spring:
  application:
    name: nacos-order-consumer  #注册服务名称
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848


#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
  nacos-user-service: http://nacos-payment-provider 
 

(4) The main startup class OrderNacosMain83.java

@EnableDiscoveryClient  //开启服务提供者或消费者,客户端的支持,用来注册服务或连接到注册中心
@SpringBootApplication  //主启动
public class OrderNacosMain83
{
    public static void main(String[] args)
    {
        SpringApplication.run(OrderNacosMain83.class,args);
    }
} 

(5) To write business classes, you need to add a RestTemplate configuration class:

@Configuration
public class ApplicationContextBean
{
    //这里就是创建一个轮询负载均衡的RestTemplate Bean
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate()
    {
        return new RestTemplate();
    }
}
@RestController
public class OrderNacosController
{
    @Resource
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    private String serverURL;

    @GetMapping("/consumer/payment/nacos/{id}")
    public String paymentInfo(@PathVariable("id") Long id)
    {
        return restTemplate.getForObject(serverURL+"/payment/nacos/"+id,String.class);
    }

}

(6) Test

insert image description here

 4. Comparison of service registration centers

Let's first understand what is the CAP model?

  • Consistency : The instance of the same request at the same time returns the same result, and all data has strong consistency.
  • Availability: The read and write requests of all instances can get correct responses within a certain period of time.
  • Partition tolerance: The system can still provide normal services when the network is abnormal.

        This is the CAP principle, also known as the CAP theorem, but the three characteristics cannot be satisfied at the same time, so the distributed system design should consider whether to choose C (consistency) or A under the premise of satisfying P (partition fault tolerance) (Availability), ie: CP or AP

        CP:

        AP:

Service Registration and Discovery Framework CAP model console management Community activity
Eureka AP support Low (2.x version closed source)
Zookeeper CP not support middle
Consul CP support high
Nacos AP/CP support high

4. Nacos Service Configuration Center

1. nacos as the configuration center----basic configuration

(1) Create a submodule:  cloudalibaba-config-nacos-client3377

(2) Write the pom file:

<!--nacos-config-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

(3) Write application.yml:

        Nacos is the same as springcloud-config. When the project is initialized, it is necessary to ensure that the configuration is pulled from the configuration center first. After the pull, the normal start of the project can be guaranteed.

        bootstrap.yml

server:
  port: 3377
spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #nacos服务注册中心地址
      config:
        server-addr: localhost:8848 #nacos作为配置中心地址
        file-extension: yaml #指定yaml格式的配置

        application.yml

spring:
  profiles:
    active: dev # 表示开发环境

(4) Create the main startup class:

@EnableDiscoveryClient
@SpringBootApplication
public class NacosConfigClientMain3377
{
    public static void main(String[] args) {
            SpringApplication.run(NacosConfigClientMain3377.class, args);
    }
}

(5) Write the business class:

@RestController
@RefreshScope //在控制器类加入@RefreshScope注解使当前类下的配置支持Nacos的动态刷新功能。
public class ConfigClientController
{
    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/config/info")
    public String getConfigInfo() {
        return configInfo;
    }
}

2. Add configuration information in Nacos

(1) Matching rules in Nacos: official documents

(2) Add configuration in Nacos

  • Configuration file naming rules :

  •  The Nacos configuration page corresponds to:

 (3) Test, start the 3377 module

        Initiate request access:  localhost:3377/config/info

        Modify the content of the configuration file. If it can be refreshed dynamically, then the configuration of Nacos Config Center is successful!

3. Nacos as a configuration center----categorical configuration (for multi-environment and multi-project management)

        First of all, let me talk about why there is a classification configuration? What role does it play in our actual development? Finally, let's actually test how to use the classification configuration.

  • In actual development, a system usually has a dev development environment, a test test environment, and a prod production environment. So how do we ensure that the service can correctly read the configuration file of the corresponding environment on Nacos when the specified environment starts?
  • A large-scale distributed micro-service system will have many micro-service sub-projects, and each micro-service project will have a corresponding development environment, test environment, pre-release environment, formal environment... How should we configure these micro-services What about management?

        To solve the above problems, nacos provides a convenient solution. Let's take a look at its graphical management interface first:

(1) The relationship between Namespace+Group+Data ID

As shown in the figure above, in simple terms, the design idea of ​​this classification configuration is similar to the package name-class name-... the outermost namespace         in java is used to distinguish the deployment environment, and Group and DataID logically distinguish two target objects ( By default: Namespac=public, Group=DEFAULT_GROUP, the default Cluster [cluster] is DEFAULT ).

  • Namespace is mainly used to achieve isolation (that is, the default namespace of nacos is public).

        Suppose we now have three environments: development, testing, and production environments, then we can create three Namespaces, and different Namespaces are isolated from each other.

  • Group defaults to DEFAULT_GROUP, and Group can divide different microservices into the same group.
  • Service is microservice. A Service can contain multiple Clusters. The default Cluster of Nacos is DEFAULT, and a Cluster refers to a virtual division of a specified microservice.

        For example, for disaster recovery, the Service microservices are deployed in the Hangzhou computer room and the Guangzhou computer room respectively. At this time, a cluster name (HZ) can be given to the Service microservice in the Hangzhou computer room, and a cluster name (HZ) can be given to the Service microservice in the Guangzhou computer room. (GZ), it can also make microservices in the same computer room call each other to improve performance.

  • The last is Instance, which is an instance of microservices.

(2) DataID configuration

First of all, we first use [default space + default grouping] to create two DataIDs of dev and test.

In the yml configuration file, spring.profile.activethe configuration file can be read in multiple environments through attributes:

 (3) Group grouping scheme ( to realize the distinction of environment )

 Add a group configuration under config. Can be configured as DEV_GROUP or TEST_GROUP

 

 (4) Namespace namespace

 Create a new namespace for dev and test:

Going back to the service list, you can find that there are more dev and test on the basis of public:

 Enter the configuration list dev namespace to create three configuration files:

         Realize namespace differentiation development environment through bootstrap+application 在config下增加一条namespace的配置即可。其值即为命名空间的ID:

Five, Nacos cluster and persistent configuration (important)

Too long, see the next article: https://blog.csdn.net/friggly/article/details/126832789

Guess you like

Origin blog.csdn.net/friggly/article/details/126303644