四、微服务框架spring cloud组件之声明式服务调用fei

2019-03-31  本文已影响0人  小manong

一、入门体验

1、搭建注册中心和服务提供者

(1)搭建eureka注册中心
server-url=http://localhost:8081/eureka/
(2)搭建eureka服务提供中心

@RequestMapping("/hello/{name}")
    public String hello(@PathVariable String name){
        return "hello "+name;
    }

2、搭建服务消费中心(使用feign)

(1)一如feign相关包,老版本用spring-cloud-starter-feign,Finchley.SR1版本的用spring-cloud-starter-openfeign

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

(2)定义接口

/**
 * 定义一个feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务
 */
@FeignClient(name = "EUREKA-CLIENT")
public interface HelloService {
    @RequestMapping("/hello/{name}")
    String hello(@PathVariable("name") String name);
}

(3)创建controller并访问

@Autowired
    private HelloService helloService;
    @RequestMapping("/hello")
    public String hello(){
        return helloService.hello("qiu");
    }

(4)开启feign服务

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class RibbonConsumer1Application {
    public static void main(String[] args) {
        SpringApplication.run(RibbonConsumer1Application.class, args);
    }
}

(5)配置

server.port=8083
spring.application.name=feign-consumer
#向注册中心注册并获取相关的服务提供者信息
eureka.client.service-url.defaultZone=http://localhost:8081/eureka/

(6)测试

3、feign调用整个流程

1、首先通过@EnableFeignCleints注解开启FeignCleint
2、根据Feign的规则实现接口,并加@FeignCleint注解
3、程序启动后,会进行包扫描,扫描所有的@ FeignCleint的注解的类,并将这些信息注入到ioc容器中。
4、当接口的方法被调用,通过jdk的代理,来生成具体的RequesTemplate
RequesTemplate在生成Request
5、Request交给Client去处理,其中Client可以是HttpUrlConnection、HttpClient也可以是Okhttp
6、最后Client被封装到LoadBalanceClient类,这个类结合类Ribbon做到了负载均衡。

二、feign一些高级功能

上一篇 下一篇

猜你喜欢

热点阅读