SpringBoot集成Nacos的详细教程

以下是SpringBoot集成Nacos的详细教程:

准备工作

  1. 下载Nacos

可以在Nacos官网中下载最新版本的Nacos服务端。

  1. 安装Nacos

解压下载的压缩包,在bin目录下运行以下命令启动Nacos服务:

bash
sh startup.sh -m standalone

运行成功后,可以通过浏览器访问 http://localhost:8848/nacos/ 来查看Nacos控制台。

  1. 创建SpringBoot工程

在IDEA或Eclipse中创建一个新的SpringBoot项目。

这里不再赘述如何创建SpringBoot项目的详细步骤,可以参考官方文档或自行搜索。

  1. 添加依赖

在pom.xml文件中添加Nacos、SpringCloud和其他相关依赖:

xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

注册服务到Nacos

在SpringBoot项目中添加以下代码,将服务注册到Nacos:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class DemoApplication {

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

    @Value("${server.port}")
    private int port;

    @Value("${spring.application.name}")
    private String serviceName;

    @PostConstruct
    public void registerToNacos() throws NacosException {
        NamingService namingService = NamingFactory.createNamingService("localhost:8848");
        namingService.registerInstance(serviceName, "localhost", port);
    }
}

其中,@EnableDiscoveryClient注解告诉Spring Boot应用程序将启用服务注册和发现,@PostConstruct注解指示方法在应用程序启动时执行。

这里通过Nacos提供的NamingService将服务注册到Nacos中,并指定了服务的名称、IP地址和端口号。

从Nacos中获取配置

在SpringBoot项目中添加以下代码,从Nacos获取配置:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
public class ConfigController {

    @Value("${config.name}")
    private String configName;

    @Value("${config.value}")
    private String configValue;

    @GetMapping("/config")
    public String getConfig() {
        return configName + ": " + configValue;
    }
}

其中,@RefreshScope注解用于在配置发生变化时重新加载Bean。

在Nacos控制台中,添加配置文件:

{
  "config": {
    "name": "demo",
    "value": "Spring Cloud Nacos Config"
  }
}

通过URL访问http://localhost:8080/config,即可获取到配置的名字和值。

示例1:Nacos服务发现

在另一个Spring Boot项目中,向Nacos注册一个服务:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class DemoApplication {

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

    @Value("${spring.application.name}")
    private String serviceName;

    @GetMapping("/service-name")
    public String getServiceName() {
        return serviceName;
    }
}

在另一个Spring Boot项目中,通过Nacos的服务发现功能,获取到注册在Nacos中的服务列表,并选择一个服务进行远程调用:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Controller
public class HelloController {

    private final RestTemplate restTemplate;
    private final DiscoveryClient discoveryClient;

    @Autowired
    public HelloController(RestTemplate restTemplate, DiscoveryClient discoveryClient) {
        this.restTemplate = restTemplate;
        this.discoveryClient = discoveryClient;
    }

    @GetMapping("/hello")
    public ResponseEntity<String> hello() {
        List<ServiceInstance> instances = discoveryClient.getInstances("demo-service");
        if (instances.size() == 0) {
            return ResponseEntity.notFound().build();
        }
        String url = instances.get(0).getUri() + "/service-name";
        return restTemplate.getForEntity(url, String.class);
    }
}

在上述代码中,通过DiscoveryClient获取服务的列表,选择第一个服务实例并从中获取其URI,在远程调用时通过这个URI调用服务的/service-name接口。

示例2:Nacos配置管理

在Spring Boot项目中,添加以下代码,读取Nacos中的配置:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@RefreshScope
public class DemoApplication {

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

    @Value("${config.name}")
    private String configName;

    @GetMapping("/config")
    public String getConfig() {
        return configName;
    }
}

在Nacos控制台中,修改配置文件内容:

{
  "config": {
    "name": "Spring Nacos Config"
  }
}

选择配置发布、更新即可看到应用程序中的新配置。

总结:

通过本文的介绍,可以看出,集成Nacos几乎于Spring Boot无缝衔接,只需简单的配置和几行代码即可实现服务注册、发现和配置管理功能。如果您已经使用了Spring Cloud相关的技术栈,那么使用Nacos将会轻松不少。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot集成Nacos的详细教程 - Python技术站

(0)
上一篇 2023年5月15日
下一篇 2023年5月15日

相关文章

  • Java实现的对称加密算法3DES定义与用法示例

    Java实现的对称加密算法3DES定义与用法示例 1. 什么是3DES 3DES(Triple DES)是一种对称加密算法,常用于数据加密、数字签名等场景。它是DES(Data Encryption Standard)算法的增强版,采取3次DES步骤进行加密,因此也被称为TDEA(Triple Data Encryption Algorithm)。 3DES…

    Java 2023年5月18日
    00
  • 如何利用Spring MVC实现RESTful风格

    以下是关于“如何利用Spring MVC实现RESTful风格”的完整攻略,其中包含两个示例。 如何利用Spring MVC实现RESTful风格 RESTful是一种Web服务架构风格,它使用HTTP协议进行通信,并使用标准的HTTP方法(GET、POST、PUT、DELETE等)来实现资源的增删改查。Spring MVC是一个基于MVC模式的Web框架,…

    Java 2023年5月16日
    00
  • SpringBoot actuator 健康检查不通过的解决方案

    本次将详细讲解SpringBoot Actuator健康检查无法通过的解决方案。 什么是SpringBoot Actuator 健康检查? SpringBoot中的Actuator是一个管理和监控SpringBoot应用程序的工具集合。Actuator主要是提供了一组RESTful API,让我们可以对应用程序进行配置、管理与监控。 SpringBoot提供…

    Java 2023年5月19日
    00
  • SpringBoot如何在运行时动态添加数据源

    让我们来详细讲解一下Spring Boot如何在运行时动态添加数据源。 1. 引入依赖 在开始之前,我们需要引入Spring Boot的依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-sta…

    Java 2023年6月3日
    00
  • Java面试题之HashMap 的 hash 方法原理是什么

    HashMap 的 hash 方法原理是什么 在了解HashMap的原理之前, 我们先看看hash散列表是怎么工作的, 他的原理是什么。 散列表的原理是将关键字通过散列函数映射到固定的位置上, 并对原始值进行处理, 最终得到的值就是我们所说的哈希值, 即在HashMap中所表现出来的值。在JDK1.7之前,HashMap的内部实现方式是数组 + 链表,数组的…

    Java 2023年5月26日
    00
  • jabsorb笔记_几个小例子第1/2页

    jabsorb笔记_几个小例子第1/2页 什么是jabsorb jabsorb是一个 JavaScript 对象表示法 (JSON) 库,它将 Java 对象转换为 JSON 格式并反向转换。它具有很高的效率和灵活性,并且易于使用。 jabsorb的使用方法 jabsorb的使用非常简单,只需要引入jabsorb的jar包,然后创建一个JSONRPCBrid…

    Java 2023年6月15日
    00
  • Zend Studio (eclipse)使用速度优化方法

    Zend Studio (Eclipse)使用速度优化方法 Zend Studio是一个在Eclipse基础上扩展的PHP IDE,提供了众多的功能,但是在使用中可能会出现卡顿、启动慢等问题。本文将给出一些常见的优化方法,以提高Zend Studio的使用效率。 1. 调整启动参数 默认情况下,Zend Studio会使用JVM的默认设置进行启动,这可能会导…

    Java 2023年6月15日
    00
  • 使用json字符串插入节点或者覆盖节点

    使用json字符串插入节点或者覆盖节点的过程可以分为以下几个步骤: 将json字符串解析为json对象 根据需要插入或覆盖的节点,生成新的json节点 将新的json节点插入或覆盖到目标json对象中 将最终结果转换为json字符串 下面通过两个示例说明具体的操作过程。 示例1:插入节点 假设原始的json字符串为: { "name": …

    Java 2023年5月26日
    00
合作推广
合作推广
分享本页
返回顶部