背景
- 客户端client 调用 服务端 provider。
- client 和 provider 共同引入公共模块依赖。
- 客户端 和 服务端共同引入公共包。
- 使用公共模块供client 和 provider继承可以较少代码量的同时可以防止填写的url出错。
- 公共包有接口如:
@Service
@RequestMapping("/refactor")
public interface HelloService{
@RequestMapping(value = "/hello4",method = RequestMethod.GET)
public String hello(@RequestParam String name);
@RequestMapping(value = "/hello5",method = RequestMethod.GET)
public User hello(@RequestParam String name, @RequestHeader Integer age);
@RequestMapping(value = "/hello6",method = RequestMethod.POST)
public String hello(@RequestBody User user);
}
客户端client调用provider流程
- client声明一个接口继承公共模块的接口 HelloService,如:
import cn.dm.service.HelloService;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
@Service
@FeignClient(value = "eureka-provider")
public interface RefactorHelloService extends HelloService {
}
- 然后就可以在 控制器 中 注入接口 RefactorHelloService 供调用所需方法,如:
import com.itheima.eurekafeignclient.service.LocalItemServiceImpl;
import com.itheima.eurekafeignclient.service.RefactorHelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LocalItemController {
@Autowired
LocalItemServiceImpl localItemServiceImpl;
@Autowired
RefactorHelloService refactorHelloService; //这个是继承
@GetMapping("/hi") //这个注解的路径需要重写继承类的结构参数
public String hi(String id) {
return localItemServiceImpl.hi(id);
}
@GetMapping("/test")
public String test(String name) {
return refactorHelloService.hello("hahahah");
}
}
服务端provider继承公共模块的接口 HelloService
- 控制器 RefactorHelloController 实现接口 HelloService,如:
import cn.dm.pojo.User;
import cn.dm.service.HelloService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RefactorHelloController implements HelloService {
@Override
public String hello(@RequestParam("name") String name) {
return "Hello " + name;
}
@Override
public User hello(@RequestParam("name") String name, @RequestHeader("age") Integer age) {
return new User(name,age);
}
@Override
public String hello(@RequestBody User user) {
return "Hello111111111 " + user.getName() + ", " + user.getAge();
}
}
运行流程
- 首先启动注册中心 eureka-server --> 服务提供者 provider --> 消费者 client。
- 在浏览器输入client看中控制器内拦截器的路径,注意get请求方式记得拼接参数。