springboot调用外部接口之openfeign

文章目录

  • 应用常见说明
  • 引入依赖
  • application.properties
  • 启动类开启
  • provider端
  • consumer端
    • Service 接口配置
    • 测试接口

应用常见说明

某个服务需要调用外部的第三方服务的接口 或者中间做目标接口的代理,使用openfeign能很好的解耦和扩展

引入依赖

        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
            <version>3.1.4version>
        dependency>

application.properties

outSide.url=192.168.79.2:8089

启动类开启

@EnableFeignClients
@SpringBootApplication
public class TestFeignApplication {

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

}

provider端

@RequestMapping("/provider")
@RestController
public class ProviderController {

    @Autowired
    PrintService printService;

    @PostMapping("outSide")
    public String outSide(@RequestBody TestDto testDto) {
        System.out.println("outSide被调用!!!");
        return printService.print(testDto);
    }

    @PostMapping("outSideAddToken")
    public String outSideAddToken(@RequestBody TestDto testDto) {
        System.out.println("outSideAddToken被调用!!!");
        return printService.print(testDto);
    }
}

consumer端

Service 接口配置

@Service
@FeignClient(url = "${outSide.url}", name = "service2")
public interface FeignDemoClient {
    @RequestMapping(value = "/provider/outSide", method = RequestMethod.POST)
    @ResponseBody
    public String getMessage(@RequestBody TestDto testDto);
}

配置了token的

@Configuration
public class FeignDemoConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //添加token
        requestTemplate.header("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ4ZGFwYXBwaWQiOiIzNDgxMjU4ODk2OTI2OTY1NzYiLCJleHAiOjE2NjEyMjY5MDgsImlhdCI6MTY2MTIxOTcwOCwieGRhcHRlbmFudGlkIjoiMzAwOTgxNjA1MTE0MDUyNjA5IiwieGRhcHVzZXJpZCI6IjEwMDM0NzY2MzU4MzM1OTc5NTIwMCJ9.fZAO4kJSv2rSH0RBiL1zghdko8Npmu_9ufo6Wex_TI2q9gsiLp7XaW7U9Cu7uewEOaX4DTdpbFmMPvLUtcj_sQ");
    }
}
@Service
@FeignClient(url = "${outSide.url}", name = "feignServer", configuration = FeignDemoConfig.class)
public interface TokenDemoClient {
    @RequestMapping(value = "/provider/outSideAddToken", method = RequestMethod.POST)
    @ResponseBody
    public String getMessage(@RequestBody TestDto testDto);
}

测试接口

@RestController
public class ConsumerController {

    @Autowired
    FeignDemoClient feignDemoClient;

    @Autowired
    TokenDemoClient tokenDemoClient;

    //测试feign调用外部接口入口
    @PostMapping("/test")
    public String test2(@RequestBody TestDto testDto) {
        return feignDemoClient.getMessage(testDto);
    }


    //测试feign调用外部接口入口,加上token
    @PostMapping("/testToken")
    public String test4(@RequestBody TestDto testDto) {
        return tokenDemoClient.getMessage(testDto);
    }
}

你可能感兴趣的:(微服务,spring,boot,java,openfeign,feign,调用外部接口)