SpringCloudFeign怎么用

这篇文章主要介绍了Spring Cloud Feign怎么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

成都创新互联,为您提供网站建设成都网站制作、网站营销推广、网站开发设计,对服务护栏打桩机等多个行业拥有丰富的网站建设及推广经验。成都创新互联网站建设公司成立于2013年,提供专业网站制作报价服务,我们深知市场的竞争激烈,认真对待每位客户,为客户提供赏心悦目的作品。 与客户共同发展进步,是我们永远的责任!

概述

在Spring Cloud EureKa Ribbon 服务注册-发现-调用一文中简单的介绍了在Spring Cloud中如何使用EureKa和Ribbon。文章中使用了RestTemplate去访问其他的restful微服务接口。其实在Spring Cloud还可以使用Feign来访问其他的restful微服务接口。使用起来更加的简洁明了。

集成Feign

修改一下Spring Cloud EureKa Ribbon 服务注册-发现-调用中order service的pom配置,把Fegin引入进来即可。

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

修改OrderApplication类,删除如下代码:

  @Bean
  @LoadBalanced
  RestTemplate restTemplate() {
    return new RestTemplate();
  }

并加上@EnableFeignClients注解。完整代码如下:

package com.springboot;

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;

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

新增接口UserService,并使用@FeignClient注解。

package com.springboot;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name="user")
public interface UserService {
  @GetMapping(value="/getUser")
  String getUser();
}

这里的@FeignClient(name="user")中的name=user表示要访问user这个微服务。由于order这个微服务已经集成了Eureka和Ribbon。那么使用@FeignClient(name="user")访问user微服务的时候,已经自动支持客户端路由了。并且会从注册中心中找到user这个微服务。

修改OrderController,注入UserService。

package com.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderController {

  @Autowired
  private UserService userService;

  @GetMapping("/getOrderUser")
  public String getOrderUser() {
    return userService.getUser();
  }
}

这样就无需使用

restTemplate.getForEntity("http://user/getUser",String.class).getBody();

来调用user服务中的getUser接口了。而是直接使用userService.getUser()就可以了。

启动注册中心以及user和order这两个微服务。使用http://localhost:8883/getOrderUser

访问一下。是可以返回

I am user list.

感谢你能够认真阅读完这篇文章,希望小编分享的“Spring Cloud Feign怎么用”这篇文章对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,更多相关知识等着你来学习!

网页题目:SpringCloudFeign怎么用
文章位置:https://www.cdcxhl.com/article16/jpsgdg.html

成都网站建设公司_创新互联,为您提供网站建设网站收录品牌网站设计服务器托管响应式网站微信小程序

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都seo排名网站优化