SpringCloud学习--OpenFeign使用

1.pom依赖


						<!-- 修改openFeign请求方式错误 -->
			       <dependency>
			            <groupId>io.github.openfeign</groupId>
			            <artifactId>feign-httpclient</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-openfeign</artifactId>
        </dependency>

OpenFeign组成:Feign+Ribbon+Hystrix
**加粗样式**

2. 配置

2.1 开启注解(服务调用方)

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class OpenfeignApplication {

    public static void main(String[] args) {
        SpringApplication.run(OpenfeignApplication.class, args);
    }

}

2.2 新建一个服务接口包common-Api

创建一个接口类

@RestController
@RequestMapping("/test")
public interface TestApi {

    @GetMapping("/hello")
    public String sayHi();

    @GetMapping("/testMap")
    public Map<String, String> getMap(@RequestParam("key") String key);

    @PostMapping("/testObj")
    public Person getPerson(@RequestBody Person person);
}

2.3 打包安装到服务提供方和服务调用方

   <dependency>
            <groupId>com.xjq.study</groupId>
            <artifactId>common-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

服务提供方实现接口类 :

 */
@Component
public class TestController implements TestApi{

    @Override
    public String sayHi() {
        return "Hello~";
    }

    @Override
    public Map<String, String> getMap(String key) {
        System.out.println(key);
        return Collections.singletonMap(key, "values");
    }

    @Override
    public Person getPerson(Person person) {
        return person;
    }
}

服务调用方继承接口

@FeignClient(value = "providers")  // value为服务提供方的服务组
public interface TestInterfaces extends TestApi{
}

服务调用方Controller:

@RestController
public class TestController {

    @Autowired
    TestInterfaces testInterfaces;

    @GetMapping("/test")
    public String getSayHi(){
        String s = testInterfaces.sayHi();
        return s;
    }

    @GetMapping("/testMap")
    public Map<String, String> getTestMap(String key) {
        System.out.println("getTestMap-key:" + key);
        Map<String, String> map = testInterfaces.getMap(key);
        return map;
    }

    @GetMapping("/testObj")
    public Person getPerson(@RequestParam("id") String id, @RequestParam("name") String name) {
        Person person = new Person(id, name);
        return  testInterfaces.getPerson(person);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值