一,创建服务消费者模块
1.1 创建步骤和上一篇类似-》新建一个spring-boot子模块,取名为feign-consumer,可以在选择dependencies时勾选Spring Web,Eureka Discovery Client,OpenFeign;也可以直接走默认,然后在它的pom文件引入Feign的起步依赖spring-cloud-starter-feign、Eureka的起步依赖spring-cloud-starter-netflix-eureka-client、Web的起步依赖spring-boot-starter-web,代码如下:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.7.RELEASE
com.zhangghq
feign_consumer
0.0.1-SNAPSHOT
feign_consumer
Demo project for Spring Boot
1.8
Greenwich.SR2
com.zhanghq
common
0.0.1-SNAPSHOT
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.cloud
spring-cloud-starter-openfeign
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
1.2 在工程的配置文件application.yml文件,指定程序名为feign-consumer,端口号为8764,服务注册地址为http://localhost:8761/eureka/ ,代码如下:
eureka:
instance:
hostname: localhost
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8764
spring:
application:
name: consumer-feign
feign:
hystrix:
enabled: true #开启断路器(熔断器) 这个注解不提示 但是不影响它的使用
1.3 在程序的启动类FeignConsumerApplication ,加上@EnableFeignClients注解开启Feign的功能:
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class FeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
}
1.4 定义一个feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务。比如在代码中调用了producer服务的“/hi”接口,代码如下:
@FeignClient(value = "producer")
public interface FeignBookService {
@RequestMapping(value = "/hi",method = RequestMethod.GET)
String sayHiFromClientOne(@RequestParam(value = "name") String name);
}
1.5 在Web层的controller层,对外暴露一个"/hi"的API接口,通过上面定义的Feign客户端FeignBookService 来消费服务。代码如下:
@RestController
public class TestController {
//编译器报错,无视。 因为这个Bean是在程序启动的时候注入的,编译器感知不到,所以报错。
@Autowired
FeignBookService feignBookService
@RequestMapping("/hi")
public String sayHi(@RequestParam String name)
{
return feignBookService.sayHiFromClientOne(name);
}
}
1.6 启动程序,多次访问http://localhost:8764/hi?name=jackson 就可以了
上一篇:Spring cloud学习之路(三,服务提供者 )https://blog.csdn.net/Zhang_Jackson/article/details/103289720
下一篇:Spring cloud学习之路(五,断路器 Hystrix)https://blog.csdn.net/Zhang_Jackson/article/details/103293354
代码已经放在了GitHub上:https://github.com/JacksonZhangHuaQuan/SpringCloudDemo