Feign进行服务间调用

Feign进行服务间调用

  • 前提:开启服务注册与发现

1、导依赖(在消费端导入)

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

2、开启Feign(消费端的启动类)

@EnableFeignClients

3、编写调用接口

package com.wagn.s.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

//name为在注册中心中的微服务名称
@FeignClient(name = "server-oss",fallback = OssFeignCallback.class)
@Component

public interface OssFeign{
    @PostMapping("/oss/remoteTest")//这里为接口全路径
    public String remoteTest(@RequestBody String id);
}

    //这是远程微服务的接口
    //@PostMapping("remoteTest")
    //public String remoteTest(@RequestBody String id){
    //    return "yes"+id;
    //}

4、绑定失败回调类

package com.wagn.s.feign;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class OssFeignCallback implements OssFeign {
    @Override
    public String remoteTest(String id) {
        return null;
    }
}

5、调用该接口实现远程服务调用

package com.wagn.s.controller;


import com.wagn.s.feign.OssFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-09-12
 */
@RestController
@RequestMapping("/s/user-pwd")
public class UserPwdController {

    @Autowired
    private OssFeign ossFeign;

    @PostMapping("remoteTest")
    public String remoteTest(@RequestBody String id){
        return ossFeign.remoteTest(id);
    }



}
posted @ 2020-09-13 09:38  天气晴21℃  阅读(293)  评论(0编辑  收藏  举报