SpringCloud微服务之服务消费者

SpringCloud微服务之服务消费者

写在前面
服务提供者和服务消费者在SpringCloud微服务中的关系。

服务提供者和服务消费者都是eureka的client都是一个web项目
服务提供者要提供一个Rest服务
服务消费者就是调用服务提供者的Rest服务
服务之间的调用使用的是http,不在是RPC,使用Feign和Ribbon框架

pom文件

<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-openfeign</artifactId>
</dependency>

服务消费者跟服务提供者都是eureka的client,所以这里同样要引入eureka-client依赖,服务消费者我们使用feign框架。
使用feign和Ribbon的好处:相比于HttpClient和OKHttp方式,多了负载均衡功能,编码更加方便。

启动类

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ConsumerApplication {

    public static void main(String[] args) {

        SpringApplication.run(ConsumerApplication.class);
    }
}

没有什么特殊的,要添加Feign的功能就@EnableFeignClients,这就是Springboot的约定优于配置的好处,方便、解耦。

application.yml

server:
  port: 8031
spring:
  application:
    name: micro-tpl-consumer
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8001/eureka

没有什么特殊的地方跟服务提供者配置几乎一样。

服务消费者调用服务提供者的rest服务

使用feign调用http服务

@FeignClient(serviceId = "micro-tpl-login")
@RequestMapping("/provider")
public interface ProviderFeignService {

    @GetMapping("/say/hi/{name}")
    String sayHi(@PathVariable("name") String name);
}

@FeignClient表示它是一个Feign请求
micro-tpl-login 就是服务提供者的spring.application.name的值,这样一来服务消费者只需要知道这个逻辑名,不需要知道服务提供者的具体的ip是那些,端口是那些,对使用方透明。
声明了一个接口这里,你也可以用一个普通类,要请求那个rest服务,使用了几个注解,@RequestMapping和@GetMapping —就是服务提供者的那个地址哈!!

扫描二维码关注公众号,回复: 2323127 查看本文章

我们在编写一个Controller来测试一下

@RequestMapping("/consumer")
public class ConsumerController {
    @Autowired
    private UserFeignService userFeignService;

    @GetMapping("/hi/{name}")
    public String sayHi(@PathVariable String name){
        return providerFeignService.sayHi(name);
    }
}

跟我们平时使用的方式都一样
启动查看eureka控制台
消费者

看到我们的消费者也注册到了eureka中。

测试http://localhost:8031/consumer/hi/zhangsan
你好:zhangsan

猜你喜欢

转载自blog.csdn.net/mayongzhan_csdn/article/details/81163252
今日推荐