zoukankan      html  css  js  c++  java
  • spring Cloud-Feign调用远端HTTP服务

    采用Feign的方式来调用Hello World服务集群。

    1. 创建Maven工程,加入spring-cloud-starter-feign依赖

    <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>

    2. 创建启动类,需呀加上@EnableFeignClients注解以使用Feign, 使用@EnableDiscoveryClient开启服务自动发现

    package springcloud.helloworld.feign.service;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.netflix.feign.EnableFeignClients;
    
    @SpringBootApplication
    @EnableDiscoveryClient
    @EnableFeignClients
    public class ServiceFeignApplication {
        public static void main(String[] args) {
            SpringApplication.run(ServiceFeignApplication.class, args);
        }
    }

    3. 添加配置文件application.yml, 使用端口8902, 名字定义为service-feign, 并注册到eureka服务中心

    eureka:
       client:
          serviceUrl:
            defaultZone: http://localhost:8761/eureka/
    server:
       port: 8902
    spring:
       application:
          name: service-feign

    4. 定义Feign:一个用@FeignClient注解的接口类,

    package springcloud.helloworld.feign.service;
    
    import org.springframework.cloud.netflix.feign.FeignClient;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    @FeignClient(value = "SERVICE-HELLOWORLD")
    public interface HelloWorldService {
        @RequestMapping(value = "/",method = RequestMethod.GET)
        String sayHello();
    }

    5. 定义一个WebController。

    sayHello()映射到http://localhost:8902/hello, 在这里,我修改了Hello World服务的映射,将根“/”, 修改成了“/hello”。

    package springcloud.helloworld.feign.service;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class WebController {
        @Autowired 
       HelloWorldService helloWorldFeignService;
    @RequestMapping(value
    = "/hello",method = RequestMethod.GET) public String sayHello(){ return helloWorldFeignService.sayHello(); } }

    6. 启动Feign应用, 访问http://localhost:8902/hello, 多次刷新,可以看到和前一章Ribbon里面的应用一样, 两个Hello World服务的输出交替出现。说明通过Feign访问服务, Spring Cloud已经缺省使用了Ribbon负载均衡。

  • 相关阅读:
    Active Url 激活URL
    Specified argument was out of the range of valid values.
    EnumHelp
    历史对像(版本对像)
    dom4j API 简介
    即时通讯软件openfire+spark+smack
    openfire插件入门学习
    Openfire本地化配置
    JSONObject与JSONArray的使用
    Android端服务器推送技术原理分析及XMPP的使用
  • 原文地址:https://www.cnblogs.com/linhongwenBlog/p/8707085.html
Copyright © 2011-2022 走看看