Spring (47)如何在Spring Cloud中实现服务发现
在Spring Cloud中实现服务发现,通常使用Eureka或Consul作为服务注册中心。以下是使用Eureka的基本步骤和示例代码:
- 添加依赖:
<!-- Eureka Discovery Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 配置application.properties或application.yml:
spring:
application:
name: service-provider
server:
port: 8762
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
- 启动类添加@EnableDiscoveryClient注解:
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);
}
}
- 服务消费者使用@LoadBalanced注解的RestTemplate来调用服务提供者:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
@Configuration
public class Config {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
服务发现功能将确保通过服务名(如service-provider
)调用时,RestTemplate会自动发送请求到注册到Eureka的服务实例。
评论已关闭