Spring Boot 项目中如何实现服务发现与负载均衡?请结合Eureka 或 Consul 以及 Ribbon 或 Spring Cloud LoadBalancer进行说明?
在Spring Boot项目中实现服务发现与负载均衡,可以使用Spring Cloud的Eureka和Ribbon。以下是一个简单的例子:
- 添加依赖到
pom.xml
:
<!-- Eureka Discovery Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- Ribbon -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
- 配置
application.properties
或application.yml
:
spring:
application:
name: service-consumer
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;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceConsumerApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ServiceConsumerApplication.class, args);
}
}
- 使用Ribbon进行服务调用:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ConsumerController {
private final RestTemplate restTemplate;
@Autowired
public ConsumerController(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@GetMapping("/call-service")
public String callService() {
return restTemplate.getForObject("http://SERVICE-PROVIDER/greeting", String.class);
}
}
在上述代码中,RestTemplate
已被标记为@LoadBalanced
,这意味着Ribbon会用来处理服务调用,并且Eureka Client会用来发现服务提供者。调用\`http://SERVICE-PROVIDER
评论已关闭