在Spring Boot和Hyperf中使用Nacos作为服务发现的示例代码如下:
Spring Boot:
- 添加依赖到
pom.xml
:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
- 配置
application.properties
或application.yml
:
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.application.name=spring-boot-service
- 启动类添加
@EnableDiscoveryClient
注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Hyperf:
- 添加依赖到
composer.json
:
"require": {
"hyperf/hyperf": "^2.2",
"hyperf/nacos-register": "^2.2"
}
- 配置
config/autoload/server.php
或config/config.php
:
return [
'nacos' => [
'host' => [
'127.0.0.1:8848',
],
'namespace' => null,
'service' => [
'name' => 'hyperf-service',
'protect_threshold' => 0.01,
],
'metadata' => [],
'weight' => 1,
'cluster' => null,
'ephemeral' => true,
'group' => 'DEFAULT_GROUP',
'username' => null,
'password' => null,
'extend_data' => [],
],
];
- 启动文件启动服务:
<?php
use Hyperf\Nacos\NacosServer;
use Hyperf\Di\Annotation\Inject;
$autoload = require_once __DIR__ . '/../vendor/autoload.php';
$autoload->addPsr4('App\\', __DIR__ . '/../src/');
$instance = make(NacosServer::class);
$instance->start();
这两个示例展示了如何在Spring Boot和Hyperf中配置Nacos作为服务注册中心。在Spring Boot中,你需要添加spring-cloud-starter-alibaba-nacos-discovery
依赖,并在application.properties
或application.yml
中配置Nacos服务器地址和应用名。在Hyperf中,你需要添加hyperf/nacos-register
依赖,并在配置文件中配置Nacos的相关参数。