springcloud系列五 feign远程调用服务

一:Feign简介

Feign 是一种声明式、模板化的 HTTP 客户端,在 Spring Cloud 中使用 Feign,能够作到使用 HTTP请求远程服务时能与调用本地方法同样的编码体验,开发者彻底感知不到这是远程方法,更感知不到这是个 HTTP 请求。web

Feign 的灵感来源于 Retrofit、JAXRS-2.0 和 WebSocket,它使得 Java HTTP 客户端编写更方便,旨在经过最少的资源和代码来实现和 HTTP API 的链接。spring

 

二:Feign使用步骤

 

在客户端集成Feign便可mybatis

第一步:pom依赖app

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

因为可能特别多的模块须要调用其余模块的项目,那么就须要进行统一依赖,减小重复依赖:负载均衡

因此将这个依赖添加至父工程里面编码

启动类添加注解开启远程调用:spa

 

package com.cxy; import com.netflix.loadbalancer.BestAvailableRule; import com.netflix.loadbalancer.IRule; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; /*** * @ClassName: PersonApplication * @Description: * @Auther: * @Date: 2019/1/2816:30 * @version : V1.0 */ @SpringBootApplication @EnableEurekaClient //开启注解,注册服务
@MapperScan("com.cxy") @EnableFeignClients public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class,args); } @Bean @LoadBalanced //使用负载均衡器Ribbon
    public RestTemplate getRestTemplate(){ return new RestTemplate(); } /*@Bean public IRule myRule(){ //return new RoundRobinRule();//轮询 // return new RetryRule();//重试 return new BestAvailableRule(); }*/ }
@EnableFeignClients,这个注解

远程调用方法首先须要写一个接口,能够看成是service:
package com.cxy.service; import com.cxy.dataObject.PersonDo; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Component @FeignClient("cxy-person-service") public interface IPersonService { @RequestMapping("/person/{id}") PersonDo getPersonDoById(@PathVariable("id") Integer id); }

contrller调用.net

 @Autowired private IPersonService personService;
**/ @RequestMapping(value = "/get/{id}",method = RequestMethod.GET) public PersonDo selectPsersonById(@PathVariable Integer id){ PersonDo personDo =personService.getPersonDoById(id); return personDo; }

启动访问:code

直接访问结果:blog

此处已经成功了

相关文章
相关标签/搜索