使用Spring Cloud搭建各种微服务之后,服务可以通过@FeignClient使用和发现服务场中的其他服务。
还是以Config Server和Config Client为例,这是服务场中的注册的两个微服务。
![这里写图片描述](https://img-blog.csdn.net/20170730212335815?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2FuZ2thbmdsb3U=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
Config Server中定义了两个服务接口(一个Post、一个Get方法)
package demo.controller;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import demo.model.User;
@RestController
@RefreshScope
public class Controller {
@GetMapping(value="s")
String helloServer(String username) {
return "Hello " + username + "!";
}
@PostMapping(value="u")
String helloUser(@RequestBody User user) {
return "Hello " + user + "!";
}
}
在Config Client(spring.application.name=test-dev)我们使用Config Server中定义的这两个微服务。
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import cn.test.bean.User;
@FeignClient(value = "config-service")
public interface FindService {
@GetMapping(value="s")
String helloServer(@RequestParam("username")String username);
@PostMapping(value="u")
String helloUser(@RequestBody User user);
}
注意,Get方法中通过@RequestParam指定需要传递的参数,应用启动时需添加@EnableFeignClients注解。
@Autowired
private FindService service;
@GetMapping("/find")
String find(String param) {
return "find " + service.helloServer(param);
}
@PostMapping("/f")
String findU(@RequestBody User user) {
return "find " + service.helloUser(user);
}
调用如下:
![这里写图片描述](https://img-blog.csdn.net/20170730213118889?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2FuZ2thbmdsb3U=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)