介绍
在微服务架构中,业务被拆分为多个微服务,服务之间的通讯基于http restful。在spring cloud中,服务调用方式有两种 1.Ribbon+RestTemplate 2.Fegin
github地址:https://github.com/erlieStar/spring-cloud-learning
建一个服务生产者
示例项目:producer-simple(spring-cloud-ribbon)
1.项目配置如下
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
application.yaml
server:
port: 8001
spring:
application:
name: producer-simple
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka
2.启动类加上@EnableEurekaClient注解
@RestController
@EnableEurekaClient
@SpringBootApplication
public class ProducerSimple {
public static void main(String[] args) {
SpringApplication.run(ProducerSimple.class);
}
@Value("${server.port}")
private String port;
@RequestMapping("hello")
public String hello(@RequestParam String name) {
return "hello, " + name + " i am from port: " + port;
}
}
启动eureka-service(spring-cloud-eureka)
接着启动2个producer-simple(spring-cloud-ribbon)
初始端口为8001,启动一个实例后,修改端口为8002,再启动一个实例
在idea中启动2个实例的方法如下
1.点击Edit Configurations
2.勾选Allow parallel run
3.依次点击如下2个按钮
访问 http://localhost:7001,可以看到有2个实例
建一个服务消费者
示例项目:consumer-ribbon(spring-cloud-ribbon)
1.项目配置如下
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
application.yaml
server:
port: 9000
spring:
application:
name: consumer-ribbon
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka
2.启动类加上@EnableEurekaClient注解
向程序注入RestTemplate,并通过@LoadBalanced注解开启客户端负载均衡
@RestController
@EnableEurekaClient
@SpringBootApplication
public class ConsumerRibbon {
public static void main(String[] args) {
SpringApplication.run(ConsumerRibbon.class);
}
@Autowired
private RestTemplate restTemplate;
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@GetMapping("hello")
public String hello(@RequestParam String name) {
return restTemplate.getForObject("http://PRODUCER-SIMPLE/hello?name=" + name, String.class);
}
}
访问http://localhost:9000/hello?name=xiaoshi
交替显示
hello xiaoshi, I am from port: 8001
hello xiaoshi, I am from port: 8002
参考博客
[1]https://www.fangzhipeng.com/springcloud/2018/08/02/sc-f2-ribbon.html
转载:https://blog.csdn.net/zzti_erlie/article/details/104092792