该案例有4个SpringBoot项目,分别为:centerdemo(注册中心)、receptiondemo(消费者)、counselordemo(提供者)、teacherdemo(提供者)。
实现目标:
1. 使用Eureka:消费者和提供者分别注册到注册中心
2. 使用Feign:通过receptiondemo 项目中TestController中的方法,调用counselordemo项目和teacherdemo项目中service包中的对应的方法。
Group:com.eurekademo
Artifact:teacherdemo
选择Web里面的Spring Web Starter
Spring Cloud Discovery里面的Eureka Server
Spring Cloud Routing里面的OpenFeign
server.port=8003
eureka.client.service-url.defaultZone=http://localhost:8888/eureka/
spring.application.name=teacher
启动类中添加注解:
@EnableEurekaServer
//开启远程调用
@ EnableFeignClients
1) 创建service包
2) 创建TeacherService类
3) 添加@RestController注解
4) 编写askTeacher方法
@RequestMapping(value="/askTeacher", method = RequestMethod.POST) public String askTeacher(){ return "xxx学习很不好!"; }
创建receptiondemo项目和counselordemo项目的过程详见下面网址:
https://cloud.tencent.com/developer/article/1449744
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启动类中增加注解,用来开启远程调用
@ EnableFeignClients
1) 创建service包
2) 创建CounselorService类
3) 添加@RestController注解
4) 编写askCounselor方法
@RequestMapping(value = "/askCounselor", method = RequestMethod.POST)
public String askCounselor(){
return "xxx打架住院了!";
}
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启动类中增加注解,用来开启远程调用
@ EnableFeignClients
1) 创建service包
2) 创建TeacherService接口
3) 添加@FeignClient注解,name的值为注册中心显示的名称。通过该注解指定调用注册中心的哪个项目。
@FeignClient(name = "TEACHER")
4) 给接口添加方法和@RequestMapping注解。
注意:接口方法和@RequestMapping注解的内容要和对应项目中的实现类的方法和注解一样。
@RequestMapping(value="/askTeacher", method = RequestMethod.POST)
public String askTeacher();
1) 创建service包
2) 创建CounselorService接口
3) 添加@FeignClient注解,name的值为注册中心显示的名称。通过该注解指定调用注册中心的哪个项目。
@FeignClient(name = "COUNSELOR")
4) 给接口添加方法和@RequestMapping注解。
注意:接口方法和@RequestMapping注解的内容要和对应项目中的实现类的方法和注解一样。
@RequestMapping(value="/askCounselor", method = RequestMethod.POST)
public String askCounselor();
类中代码如下:
@Controller
public class TestController {
@Resource
private TeacherService teacherService;
@Resource
private CounselorService counselorService;
@RequestMapping("/askTeacher")
@ResponseBody
public String askTeacher(){
String result = teacherService.askTeacher();
return "Teacher的回复是:"+result;
}
@RequestMapping("/askCounselor")
@ResponseBody
public String askCounselor(){
String result = counselorService.askCounselor();
return "Counselor的回复是:"+result;
}
@RequestMapping("/askSelf")
@ResponseBody
public String askSelf(){
return "这是我自己的回复";
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。