Spring Cloud 入门 -- 搭建Eureka注册中心 实现服务者与消费者的服务调用
以下是使用Spring Cloud搭建Eureka注册中心,并实现服务提供者和消费者的简化示例代码:
Eureka Server 注册中心:
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
application.yml:
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
服务提供者:
@EnableEurekaClient
@SpringBootApplication
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
application.yml:
spring:
application:
name: provider-service
server:
port: 8080
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
服务消费者:
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
application.yml:
spring:
application:
name: consumer-service
server:
port: 8081
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
在这个例子中,我们创建了一个Eureka Server和一个服务提供者与一个服务消费者。服务提供者注册到Eureka Server并定期心跳,消费者通过Eureka Server获取服务列表,并通过Spring Cloud的负载均衡器进行调用。这个简化的例子展示了服务注册与发现的基本流程。
评论已关闭