Spring Cloud构建微服务架构服务注册与发现,意外收获字节跳动内部资料
在Spring Cloud中,服务注册与发现通常使用Eureka来实现。以下是一个简单的例子:
- 添加依赖到
pom.xml
:
<dependencies>
<!-- Spring Cloud Eureka Server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</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>
- 配置application.yml:
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
- 启动类添加
@EnableEurekaServer
注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
以上代码创建了一个简单的Eureka服务注册中心。服务提供者和服务消费者将会在这里注册并且相互发现。这是微服务架构中一个非常关键的部分。
评论已关闭