Spring Cloud Eureka 入门 服务提供者详解
在Spring Cloud Eureka中,服务提供者是指提供服务接口的应用程序实例。以下是创建一个服务提供者的步骤和示例代码:
- 创建一个Spring Boot项目,并添加必要的依赖。
<dependencies>
<!-- Spring Cloud Eureka 客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 其他依赖... -->
</dependencies>
- 在
application.properties
或application.yml
中配置Eureka服务器的地址。
# application.properties
spring.application.name=service-provider
server.port=8080
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
- 在主应用类上添加
@EnableDiscoveryClient
注解或@EnableEurekaClient
注解来标识这是一个Eureka客户端。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceProviderApplication.class, args);
}
}
- 创建你的服务接口,并通过RestController或其他方式暴露。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ServiceController {
@GetMapping("/hello")
public String hello() {
return "Hello from Service Provider!";
}
}
启动服务提供者应用后,它将自动注册到Eureka服务器,并通过服务ID对外提供服务。其他服务可以通过Eureka发现机制来调用这个服务提供者的接口。
评论已关闭