Nacos introduction

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

Nacos helps you build, deliver, and manage microservices platforms more agile and easily. Nacos is the service infrastructure for building modern “service” centric application architectures (e.g., microservices paradigm, cloud native paradigm).

Key features of Nacos

  • Service discovery and service health monitoring
  • Dynamic configuration service, with management interface, supports rich configuration dimensions.
  • Dynamic DNS Service
  • Services and their metadata management

Nacos download and deployment

Nacos Quick start or directly download zip package, deployment download

Summary of problems encountered during Windows environment deployment

JDK Version Requirements

Note that the JDK version requires 64bit JDK 1.8+

To run an error

Run startup. CMD, and then blink. CMD command, add pause in the last line of the startup. CMD script, and the error message is displayed:

Exception in thread "main" java.lang.UnsupportedClassVersionError: org/springfra mework/boot/loader/PropertiesLauncher : Unsupported major, minor version 52.0 at Java lang. This. DefineClass1 (Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:14 2) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)Copy the code

The reason for the above problem is that I have some older projects on my computer that use JDK 1.7, so the project uses JDK1.7 and JDK1.8 interchangeover. In CMD, check the version java-version output and then 1.8.0_211 (only the highest version will be output)

The solution

  • Add environment variables to javA_HOME. Add environment variables to jdk1.8
C:\Users\Administrator>set Java_HOME JAVa_HOME =D:\Program Files\Java\jdk1.7.0_71 C:\Users\Administrator>set Java8_HOME JAVA8_HOME = D: \ \ Program Files \ Java \ jdk1.8.0 _201 C: \ Users \ Administrator >Copy the code
  • Modify the startup. CMD script to use the java8_HOME variable so that it calls JDk1.8 correctly instead of JDk1.7
if not exist "%JAVA8_HOME%\bin\java.exe" echo Please set the JAVA8_HOME variable in your environment, We need java(x64)!  jdk8 or later is better! & EXIT /B 1 set "JAVA=%JAVA8_HOME%\bin\java.exe"Copy the code

Instead, change JAVA_HOME to JAVA8_HOME and run startup. CMD. Nacos is now running correctly

Check the interface

Start-up success, on the browser visit: http://localhost:8848/nacos, will jump to the login page, the default login user name nacos, password for nacos.

After logging in successfully, you can operate the management interface

Register and discover using the Nacos service

To use NACOS, add the necessary dependencies to POM.xml

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <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>
        </dependencies>
    </dependencyManagement>
Copy the code

Service registration and discovery sample code creation

In this case, three services are registered with Nacos, Ali-nacos-provider is the service provider, ali-Nacos-consumer-ribbon is the load balancing ribbon consumer, ali-nacos-consumer-Feign is the declarative service invocation consumer ali-nacos-consumer-Feign

What is the ribbon and Feign

Create the service provider Ali-nacos-provider

Pom.xml adds nacOS dependencies

    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
Copy the code

Application. Yml configuration

server:
  port: 9000  # Specify port 9000

spring:
  application:
    name: ali-nacos-provider  # service name
  cloud:
    nacos:
      discovery:
        server-addr: 127.0. 01.: 8848 Service register address (nacOS default port 8848)

management:
  endpoints:
    web:
      exposure:
        include: The '*'
Copy the code

The startup class adds the @enableDiscoveryClient annotation

package com.easy.aliNacosProvider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
public class AliNacosProviderApplication {

    public static void main(String[] args) { SpringApplication.run(AliNacosProviderApplication.class, args); }}Copy the code

Write hello service interface helloController.java

package com.easy.aliNacosProvider;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class HelloController {
    @GetMapping(value = "/hello/{str}", produces = "application/json")
    public String hello(@PathVariable String str) {
        log.info("----------- Received consumer request -----------");
        log.info("Received parameters from consumer:" + str);
        String result = "I'm a service provider. Nice to meet you." + str;
        log.info("Provider returns result:" + result);
        returnresult; }}Copy the code

Create ribbon service consumers

Pom.xml adds nocos and ribbon dependencies

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

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

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

    </dependencies>
Copy the code

application.yml

server:
  port: 9100

spring:
  application:
    name: ali-nacos-consumer-ribbon
  cloud:
    nacos:
      discovery:
        server-addr: 127.0. 01.: 8848
Copy the code

The service calls homecontroller.java

package com.easy.ancRibbon;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Slf4j
public class HomeController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping(value = "/", produces = "application/json")
    public String home(a) {
        log.info("-----------------consumer call started -----------------");
        String param = "Yun";
        log.info("Consumer passing parameters:" + param);
        String result = restTemplate.getForObject("http://ali-nacos-provider/hello/" + param, String.class);
        log.info("Received response from provider:" + result);
        return "Ribbon Consumer,"+ result; }}Copy the code

Enable class AncRibbonConsumerApplication. Java

package com.easy.ancRibbon;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
public class AncRibbonConsumerApplication {

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

    public static void main(String[] args) { SpringApplication.run(AncRibbonConsumerApplication.class, args); }}Copy the code

Create feign service consumers

pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>
Copy the code

application.yml

server:
  port: 9101

spring:
  application:
    name: ali-nacos-consumer-feign
  cloud:
    nacos:
      discovery:
        server-addr: 127.0. 01.: 8848
  main:
    allow-bean-definition-overriding: true  # allow same beanName
Copy the code

Now let’s note that allow-bean-mrit-41 is set to true and can now be looked at as follows:

Error:  Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=trueCopy the code

Here is a detailed description of the cause of the problem

Apply for service helloService.java

package com.easy.ancFeign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient("ali-nacos-provider")
public interface HelloService {

    @RequestMapping(path = "hello/{str}")
    String hello(@RequestParam("str") String param);

}
Copy the code

The service calls homecontroller.java

package com.easy.ancFeign;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class HomeController {

    @Autowired
    private HelloService helloService;

    @GetMapping(value = "/", produces = "application/json")
    public String home(a) {
        log.info("-----------------consumer call started -----------------");
        String param = "Yun";
        log.info("Consumer passing parameters:" + param);
        String result = helloService.hello(param);
        log.info("Received response from provider:" + result);
        return "Feign Consumer"+ result; }}Copy the code

Start the class AncFeignConsumerApplication. Java

package com.easy.ancFeign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients(basePackages = {"com.easy.ancFeign"})
public class AncFeignConsumerApplication {
    public static void main(String[] args) { SpringApplication.run(AncFeignConsumerApplication.class, args); }}Copy the code

Use the sample

The existing three projects are as follows

Ali-nacos-provider: service provider 1, service name: Ali-nacos-provider, port: 9000 Ali-nacos-consumer-ribbon: Ribbon service consumer, service name: Ali-nacos-consumer-ribbon, port: 9100 Ali-nacos-consumer-Feign: Feign Consumer, service name: Ali-nacos-consumer-Feign, port: 9101

Run the test

First, start the service registry NACOS. Second, start three services, ali-nacOS-Provider, Ali-Nacos-consumer-ribbon and Ali-Nacos-consumer-Feign respectively

  • Address: http://localhost:9100/, back to: Ribbon Consumer. I’m a service provider. Nice to meet you.
  • Visit address: http://localhost:9101/, back to: FeIGN Consumer I’m a service provider, nice to meet you ==> Yuntian, indicating that FeIGN consumer fee is successful.
  • Access the address: http://localhost:9000/hello/yuntian, return: I am a service provider, glad to meet you = = > yuntian, the service provider to access the success (PS: the service provider is not made public, how hidden interface is introduced in the next article)
  • Access the address: http://localhost:8848/nacos/#/login, enter the user: nacos, password: nacos. Enter the service management interface, you can see the three services we run in the service Management-service list.

data

  • Spring Cloud Alibaba example source code
  • Nacos website