SpringCloud(4)-通過Ribbon/Feign兩種方式請求服務

服務的消費者

在上一個博客中,已經講述瞭如何搭建一個服務提供者,並註冊到eureka註冊中心去。在這一博客,主要介紹,如何請求提供的服務。我們有兩種方式去請求別人提供的服務,ribbon+RestTemplate或者Feign這兩種方式請求

使用Ribbon+restTemplate請求

  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>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
    </dependency>
    
  2. application.properties配置文件的配置

    server.port=85
    spring.application.name=consume
    eureka.client.service-url.defaultZone=http://master:81/eureka/
    
  3. 啓動類

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    
    @SpringBootApplication
    @EnableDiscoveryClient
    public class EurekaHelloConsumeApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(EurekaHelloConsumeApplication.class, args);
        }
    }
    
  4. 配置RestTemplate

    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.client.RestTemplate;
    
    @Configuration
    public class config {
        //@LoadBalanced 負載均衡
        @Bean
        @LoadBalanced
        RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }
    
  5. service層使用restTemplate來請求

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.web.client.RestTemplate;
    
    @Service
    public class ConsumeService {
        @Autowired
        private RestTemplate restTemplate;
        public String consumeHello(){
            //provider 是你提供者的spring.application.name的值
            return restTemplate.getForObject("http://provider?name=test",String.class);
        }
    }
    

使用Feign來請求

  1. 使用fegion的方式來請求,使請求變得更簡單,只需要定義一個接口,在接口上面註解FeignClient

    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @FeignClient(value = "provider")
    public interface FegionService {
    
        @RequestMapping(method = RequestMethod.GET)
         String feignHello(@RequestParam(value = "name") String name);
    }
    
  2. 在啓動類上註解

    @EnableFeignClients
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章