文章目录
前一篇讲了服务中心和服务提供,Feign基于前一篇的基础上,实现服务调用。
这种服务调用,不直连服务提供者,而是通过服务中心中转,可实现负载均衡,熔断降级等一系列操作。
服务提供可以使用上一篇的服务,也可以新建服务。这里温故一下,新建两个服务提供者。然后再建一个服务消费者,如下图:
1. 服务提供
新建两个项目,都勾选eureka discovery。
1.1 pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
1.2 application配置
两个配置文件分别是:
spring:
application:
name: two-product
server:
port: 8810
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8800/eureka/
spring:
application:
name: two-product
server:
port: 8811
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8800/eureka/
此处,两个名称要一样,可以测试负载均衡
1.3 application注解
添加@EnableDiscoveryClient注解
@SpringBootApplication
@EnableDiscoveryClient
public class TwoProduct2Application {
public static void main(String[] args) {
SpringApplication.run(TwoProduct2Application.class, args);
}
}
1.4 运行服务
运行上一篇的服务中心(单台),然后运行上面两个服务提供者。
2. 服务调用(消费)
这里,通过Feign来实现,Feign基于Ribbon实现,相对于Ribbon,基于注解,更便于编写。
2.1 pom.xml
新建一个Springboot,勾选Eureka Discovery和Feign。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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-openfeign</artifactId>
</dependency>
2.2 application配置
spring:
application:
name: two-consume
server:
port: 8820
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8800/eureka/
2.3 application注解
添加服务发现注解@EnableDiscoveryClient,添加@EnableFeignClients客户端
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class TwoConsumeApplication {
public static void main(String[] args) {
SpringApplication.run(TwoConsumeApplication.class, args);
}
}
2.4 服务接口
@FeignClient(name = "two-product")
public interface HelloService {
/**
* 此处方法名可以不一样,注意:必须写@RequestParam,否则参数传不到服务中心
* @param name
* @return
*/
@RequestMapping("/hello")
// String index(@RequestParam("name") String name);
String hello(@RequestParam("name") String name);
}
添加@FeignClient注解,配置服务提供者two-product,然后像写接口一样,添加一个方法,方法名可以和服务提供者方法名不一样,地址配置要一样,并且需要添加参数注解,否则调用不通。
2.5 对外接口
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello/{name}")
public String index(@PathVariable("name")String name) {
return helloService.hello(name);
}
}
调用注册的服务提供者。
2.6 运行服务消费
如下,可以看到,两个生产者,一个消费者:
http://localhost:8820/hello/Steven
调用这个接口,多调用几次,可以看到如下
Hello Steven, this is from product1
Hello Steven, this is from product2
Feign实现服务调用完成,并且实现了负载均衡。