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
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章