OpenFegin无注册中心的使用

starlin 3,655 2022-05-04

本篇记录了本人使用OpenFegin作为http客户端的简单使用,虽然比直接使用http调用方式会有点开销,但是还是值得试试。
这里使用springboot的方式来搭建相关的环境

定义fegin接口

接口定义如下:

@FeignClient(url="http://localhost:8080", name = "pServer",path="/p1Server")
public interface P1Service {

    @GetMapping(value = "/getName")
    String getName(@RequestParam String name);
}

@FeignClient :该注解是启用fegin必须的,其中的url是服务请求地址,name是服务名(全局唯一),path是服务路径前缀(不能使用requestMapping)

定义对应的controller接口

该Controller接口定义和SpringMvc的定义没有什么区别,不过要值得注意的是:需要与上面接口地址中的路径保持一致,如下:

@RestController
@RequestMapping(value = "/p1Server")
public class ProviderController {
    @RequestMapping(value = "/getName")
    public String getName1(String name) {
        return "hello:   " + name;
    }
}

在启动类增加@EnableFeignClients注解

需启动服务

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

编写测试方法

将之前定义的P1Service接口注入即可

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestFegin {
    @Autowired
    private P1Service p1Service;

    @Test
    public void test() {
        System.out.println(p1Service.getName("starlin"));
    }

}

输出的结果为:

hello: starlin111

以上就是用OpenFegin作为http客户端的简单使用,End,感谢阅读!!!