首页 > 其他分享 >Spring cloud集成 Nacos实现服务注册与发现

Spring cloud集成 Nacos实现服务注册与发现

时间:2022-12-08 16:37:48浏览次数:41  
标签:spring Spring boot Nacos springframework org import cloud


Nacos服务注册与发现

​​Centos7下Nacos安装和部署​​

​​spring cloud集成 NACOS配置中心实现动态配置​​

服务模块之间本来是互相独立的 不能相互访问 Nacos提供的注册服务,可以支持他们互相调用

1.启动nacos:

Spring cloud集成 Nacos实现服务注册与发现_maven

2.创建Maven工程:

我的工程结构如下:

Spring cloud集成 Nacos实现服务注册与发现_spring_02

Maven父工程pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.naixin</groupId>
<artifactId>lgn-cloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springcloud-lgn</name>
<description>搭建springcloudalibaba 第一版</description>

<packaging>pom</packaging>

<properties>
<java.version>1.8</java.version>
</properties>

</project>

3.创建服务提供者模块

目录结构:

Spring cloud集成 Nacos实现服务注册与发现_ide_03

nacos服务提供者模块pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.naixin</groupId>
<artifactId>nacos-publisher</artifactId>
<version>1.0</version>

<name>nacos-provider</name>

<description>nacos服务提供者模块</description>

<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>


<dependencies>

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

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

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-alibaba-nacos-discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.14</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>

</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

程序的启动端口为8011,应用名为nacos-providerr,向nacos server注册的地址为192.168.8.150:8848。

application.yml:

server:
port: 8011
spring:
application:
name: nacos-provider
cloud:
nacos:
discovery:
server-addr: 192.168.8.150:8848 #服务发现地址

启动类:NacosProviderApplication:

然后在Spring Boot的启动文件NacosProviderApplication加上@EnableDiscoveryClient注解,代码如下:

package com.naixin.nacosPor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.net.InetAddress;

/**
* nacos服务提供者
*/
@SpringBootApplication
@EnableDiscoveryClient //@EnableDiscoveryClient都是能够让注册中心能够发现,扫描该该服务。
@Slf4j
public class NacosProviderApplication {

public static void main(String[] args) throws Exception {

ConfigurableApplicationContext application = SpringApplication.run(NacosProviderApplication.class, args);

Environment env = application.getEnvironment();
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Login: \thttp://{}:{}/\n\t" +
"----------------------------------------------------------",
env.getProperty("spring.application.name"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"));


System.out.println("╭フ哇、內誰說↘生活萁拾狠简单濄勒今天鹫是明天⊕_⊙");
}

}

Controller类,ProviderController:

package com.naixin.nacosPor.web.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* rabbitMq 服务提供者
* Created by liangguannan on 2021/10/26.
*/
@RestController
@RequestMapping("/nacosProvider")
public class ProviderController {

@RequestMapping("/getNacosInfo")
public String getNacosInfo() {
return "输出一下:nacos 服务提供者!";
}


}

customer模块同理

application.yml:注意端口号不要冲突:

nacos服务提供者模块pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.naixin</groupId>
<artifactId>nacos-customer</artifactId>

<version>1.0</version>

<name>nacos-customer</name>

<description>nacos 消费者</description>

<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>

<dependencies>

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

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

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-alibaba-nacos-discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>

<!-- spring-cloud-starter-ribbon提供客户端的软件负载均衡算法-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>

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

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

<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.14</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>

</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

工程结构:

Spring cloud集成 Nacos实现服务注册与发现_rabbitmq_04


服务消费模块NacosCustomerApplication:

package com.naixin.nacosPor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.net.InetAddress;

/**
* nacos服务消费方
*/
@SpringBootApplication
@EnableDiscoveryClient //@EnableDiscoveryClient都是能够让注册中心能够发现,扫描该该服务。
@Slf4j
@EnableFeignClients("com.naixin.nacosPor.web.service") //添加注解@EnableFeignClients开启OpenFeign 如果不写包名默认找启动类包下面的feignClient
public class NacosCustomerApplication {

public static void main(String[] args) throws Exception {

ConfigurableApplicationContext application = SpringApplication.run(NacosCustomerApplication.class, args);

Environment env = application.getEnvironment();
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Login: \thttp://{}:{}/\n\t" +
"----------------------------------------------------------",
env.getProperty("spring.application.name"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"));


System.out.println("╭フ哇、內誰說↘生活萁拾狠简单濄勒今天鹫是明天⊕_⊙");
}

}

服务消费者是通过两种方式进行服务调用!
方式1:
RestTemplate+Ribbon的方式来进行服务调用的。
CustomerController:

package com.naixin.nacosPor.web.controller;

import com.naixin.nacosPor.web.config.HttpUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
* rabbitMq 服务消费者
* Created by liangguannan on 2021/10/26.
*/
@RestController
@RequestMapping("/nacosCustomer")
public class CustomerController {

/**
* 使用使用restTemplate方式
* @return
*/
@RequestMapping(value = "/getNacosInfo", method = RequestMethod.GET)
public String getNacosInfo() {
HttpUtils httpUtils=new HttpUtils();//服务消费者是通过RestTemplate+Ribbon的方式来进行服务调用的。
return httpUtils.restTemplate().getForObject("http://nacos-provider/nacosProvider/getNacosInfo", String.class);
}
}

HttpUtils:

package com.naixin.rabbitmq.web.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
* Http请求工具类
* @author lgn
* @version 1.0
* @date 2021/10/26 16:43
*/
public class HttpUtils {
/**
* 使用spring框架,可以使用restTemplate来进行http连接请求
* @return
*/
@LoadBalanced //负载均衡(该注解标记使用哪种负载均衡策略,服务名访问必须使用)
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}

}

方式2:
通过feign,建里CustomerFeignController:

package com.naixin.nacosPor.web.controller;

import com.naixin.nacosPor.web.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author lgn
* @version 1.0
* @date 2021/10/27 14:32
*/
@RestController
@RequestMapping("/nacosCustomer")
public class CustomerFeignController {

@Autowired
private CustomerService customerService;

/**
* 使用使用FeignClient方式
* @return
*/
@GetMapping("/feign")
public String feignTest() {
return customerService.helloNacos();
}
}

CustomerService:

package com.naixin.nacosPor.web.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

/**
* @author lgn
* @version 1.0
* @date 2021/10/27 14:14
*/
@FeignClient("nacos-provider")//服务提供者的服务名
public interface CustomerService {

@GetMapping("nacosProvider/getNacosInfo")//服务提供者的接口名
String helloNacos();
}

注册

服务者消费者服务均运行起来,可以看到在nacos里看到这两个服务已经注册成功:

Spring cloud集成 Nacos实现服务注册与发现_rabbitmq_05


Spring cloud集成 Nacos实现服务注册与发现_maven_06

服务调用

nacos作为服务注册和发现组件时,在进行服务消费,可以选择RestTemplate和Feign等方式。这和使用Eureka和Consul作为服务注册和发现的组件是一样的,没有什么区别。这是因为spring-cloud-starter-alibaba-nacos-discovery依赖实现了Spring Cloud服务注册和发现的相关接口,可以和其他服务注册发现组件无缝切换。

访问一下接口:

Spring cloud集成 Nacos实现服务注册与发现_ide_07

在浏览器上访问:http://10.10.197.85:8012/nacosCustomer/feign,可以在浏览器上展示正确的响应,这时service-customer调用service-provider服务成功。

Spring cloud集成 Nacos实现服务注册与发现_rabbitmq_08


Spring cloud集成 Nacos实现服务注册与发现_spring cloud_09


标签:spring,Spring,boot,Nacos,springframework,org,import,cloud
From: https://blog.51cto.com/u_15906694/5922711

相关文章

  • spring mvc环境之数据库的基本配置(八)
    springmvc环境之数据库的基本配置统一步骤:1.pox.xml文件引入jar包。2.resources文件建立数据库的配置信息3.在applicationContent.xml文件配置数据源bean,让spring容器......
  • 基于xml的Spring配置二(Bean 实例化的基本流程)
    Spring容器在初始化时,会将xml配置的的信息封装成一个BeanDefinition对象,所有的BeanDefinition存储到一个名为beanDefinitionMap的Map集合中去,Spring框架在对该Map......
  • Springboot 整合RabbitMQ.
    先看一下项目结构:首先创建rabbitmq-publisher:pom.xml<dependencies><dependency><groupId>org.springframework.boot</groupId><arti......
  • springboot最核心的三个特有注解
    SpringBoot最大的特点是无需XML配置文件,能自动扫描包路径装载并注入对象,并能做到根据classpath下的jar包自动配置。所以SpringBoot最核心的3个注解就是:@Config......
  • Spring:资源管理
    java标准资源管理职责说明面向资源文件系统、artifact(jar、war、ear文件)以及远程资源(HTTP、FTP等)API整合ClassLoader#getResource、java.io.File、java.ne......
  • springboot jpa创建表自动添加注释
    @Retention(RetentionPolicy.RUNTIME)@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})public@interfaceComment{Stringvalue()default......
  • spring mvc中modelattribute和sessionatrribute
    摘自http://tengj.top/2016/05/02/springmvcyuanli/SpringMVC支持使用@ModelAttribute和@SessionAttributes在不同的模型和控制器之间共享数据......
  • spring batch不错的教程
    springbatch不错的资料教程中文:​​​http://www.ibm.com/developerworks/cn/java/j-lo-springbatch1/​​​http://www.ibm.com/developerworks/......
  • 使用WGCLOUD做服务指标监控可视化之监测服务器时间
    WGCLOUD监控平台有个自定义监控项模块,可以帮助我们做一些常规监控做不到的指标监测比如用来实现我们的特殊需求场景,比如监测主机的系统时间,监测某个文件的大小,定期执行计......
  • SpringCloud组件入门使用
    SpringCloud1、远程调用1.1、微服务远程调用RestTemlpate1.2、微服务远程调用-Feign 2、Eureka注册中心2.1、Eureka注册中心搭建及入门使用2.2、Ribbon负载均......