SpringCloudAlibaba Microservice Practical Series (1) Nacos Service Registration Discovery

SpringCloudAlibaba Microservice Practical Series (1) Nacos Service Registration Discovery

Do a background understanding before actual combat.

Monolithic architecture, SOA and microservices

Monolithic architecture: With the rapid development of technology in recent years, various services have entered the network. When publishing a single architecture, you only need to publish it as a war or jar package; however, as business volume surges or website traffic increases, fatal flaws will inevitably be exposed.

SOA: Service Oriented Architecture service-oriented architecture. It aims to improve code reusability and scalability, reduce coupling, etc. For example, in a takeout process, food delivery distribution is a service, and SMS notification is also a service. These services are deployed independently and call each other through the network (HTTP, etc.) to form a complete service system.

Microservices: Microservices are composed of multiple small services with a single function. Services can be split according to business; these services are deployed independently; different services can use different technologies (different languages ​​or databases, etc.); services Lightweight protocols such as HTTP are used to interactively transmit data, which can be regarded as a more fine-grained SOA architecture.

Advantages and Disadvantages of Microservices

advantage:

  • 代码复杂度低: According to the fine-grained division of business, the business functions are clear and clear, small in size, and easy to understand and maintain.
  • Technology selection is not limited: a single service can be implemented in different languages ​​and technology stacks according to its own business
  • 独立部署: The deployment has a small impact
  • Service scalability: When the load capacity of some services is large, several more node loads can be deployed. When the load capacity is small, a few nodes can be reduced to save server resources.
  • 错误隔离: Among multiple services, the downtime of one service will not affect the operation of the entire system.
  • Branching databases is easier: different services connect to different databases

shortcoming:

  • The architecture system is complex: it is not a simple service call, the impact of network delays and failures must be fully considered, and message middleware may be required if necessary.
  • Service dependency: For example, service A calls B, and then B calls C. When C service changes, both B and A need to make changes.
  • 数据一致性问题:典型的分布式事务的问题
  • Difficulty troubleshooting interfaces: when using multiple services, you need to view their logs at the same time
  • Deployment and operation and maintenance: Checking and monitoring the health status of multiple services, rapid deployment, and dynamic scaling of services based on service load are no small challenges.

SpringCloud technology stack

In order to better manage microservices, SpringCloud technology was born. Commonly used technology stack implementations:

technology stack Technology stack implementation
Service registration and discovery Eureka、Zookeeper、Consul、Nacos
Circuit breaker, downgrade, current limiting Hystrix、Sentinel
service call Ribbon、LoadBalancer、Feign、OpenFeign、Dubbo
Configuration Config、Zookeeper、Consul、Nacos
gateway Zuul、Gateway
message bus Bus、Nacos

The above technical implementation solutions include Spring Cloud Netflix and Spring Cloud Alibaba. We only use Alibaba for this series.

The following technology stacks:

  • Nacos: do configuration and service registration discovery
  • RocketMQ: Alibaba’s distributed messaging middleware, providing reliable message publishing and subscription
  • Sentinel: Provides service current limiting, downgrading, and circuit breaker functions
  • Seata: Solve distributed transaction problems (ensure data consistency)

Start actual combat

environment

Before actual combat, first ensure our development environment:

  • java8
  • maven
  • IDEA tools
  • mysql 5.7 and above

Note: If IDEA does not match the version of Maven, an error will be reported. Unable to import maven project. Adjust the version yourself.

Getting Started with SpringBoot

When creating a project, the first thing to pay attention to is whether it is compatible with the versions of Spring Cloud and Alibaba. Check whether the versions of Spring Boot and cloud are compatible.

Insert image description here

You can create a project on the spring official website or Alibaba Cloud's webpage. First create a project and import it into IDEA.

Insert image description here

导入后将SpringBoot版本改为2.6.11的即可

Then create sub-modules (servers and consumers), and do version dependency management in the parent project:

<properties>
   <java.version>8</java.version>
   <boot.version>2.6.11</boot.version>
   <cloud.version>2021.0.4</cloud.version>
   <cloud.alibaba.version>2021.0.4.0</cloud.alibaba.version>
</properties>

<dependencyManagement>
    <dependencies>
        <!--springboot依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!--cloud的依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!--cloud.alibaba依赖-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${cloud.alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
   <plugins>
      <!--指定Maven的插件,和编译的jdk版本,若不指定maven3默认使用jdk1.5-->
      <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>3.7.0</version>
         <configuration>
            <source>1.8</source>   <!--源代码使用的jdk版本-->
            <target>1.8</target>   <!--编译后生成的class文件的版本-->
            <encoding>UTF-8</encoding> <!--字符编码集-->
         </configuration>
      </plugin>
   </plugins>
</build>

Installation and configuration of nacos

注意:nacos需要依赖jdk环境,必须是1.8及以上的版本

nacos download page: https://github.com/alibaba/nacos/releases

Insert image description here

Just check the corresponding version and download it.

After the download is completed, the cmd command window will start.

Note: If you download version 2.2.1 and above, nacos sets the default key to empty. We need to add it manually and then start it.

In the nacos configuration file application.properties

nacos.core.auth.plugin.nacos.token.secret.key=SecretKey012345678901234567890123456789012345678901234567890123456789

Start nacos

startup.cmd -m standalone

After the startup is completed, log in to the nacos URL and look at http://localhost:8848/nacos. The default username and password are nacos.

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-8JFqOEqA-1690075432821)(../imgs1/5.png)]

Simple integration of nacos

Create three sub-projects, namely provider8001, , provicer-8002and consumer9001, then register into nacos and implement remote calling through Ribbon.

The project structure is as shown in the figure. The three projects are引入健康监控和nacos的服务注册发现

Insert image description here

Configuration file taking the consumer project as an example

server:
  port: 8001
spring:
  application:
    name: provider # 应用名

  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # nacos服务地址

legend:

Insert image description here

Startup classes and annotations:

@SpringBootApplication
@EnableDiscoveryClient
public class ProviderApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(ProviderApplication.class, args);
    }
}

Start three projects to view changes in the nacos service page.
Insert image description here

The service has been registered, and there are two instances of provider, no problem~

Use RestTemplate+Ribbon to implement simple remote calls

The service provider provides the interface (write both providers)

@RestController // @RestController注解是@Controller+@ResponseBody
public class TestController {
    
    
    @Value("${server.port}")
    private String port; // 获取配置文件中写的程序端口号
    @RequestMapping("/test") // 标记是该方法的请求
    public String test() {
    
    
        return "hello world test " + port;  // 返回值是一个字符串,因为用了@RestController所以不必额外加@ResponseBody了
    }
}

Consumers also need to introduce the dependency of loadbalancer. In higher versions, they need to introduce it manually.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

The service consumer uses JavaConfig to complete the configuration class. The code is as follows:

@Configuration
public class GenericConfiguration {
    
     // 常规配置类
    @LoadBalanced // 标注此注解后,RestTemplate就具有了客户端负载均衡能力
    @Bean
    public RestTemplate restTemplate(){
    
     // 创建RestTemplate,并交个Spring容器管理
        return new RestTemplate();
    }
}

Consumer call interface

@RestController
public class TestController {
    
    

    private final String SERVER_URL = "http://provider"; // 这里的服务地址填写注册到Nacos的应用名称
    @Resource
    private RestTemplate restTemplate;
    @RequestMapping("/test")  // 标记是该方法的请求
    public String test() {
    
    
        return restTemplate.getForObject(SERVER_URL + "/test", String.class);//调用提供者/test接口
    }

}

Start project test call execution:

curl localhost:9001/test

Insert image description here

You can see the effects of remote calls and simple load implementations.

Guess you like

Origin blog.csdn.net/weixin_45248492/article/details/131876248