tianlong 2020-04-19
SpringCloud实战项目全套学习教程连载中
面试刷题
的开源系统,可以用零碎时间利用小程序查看常见面试题,夯实Java基础。示例:查询用户的学习时长
用户微服务passjava-member调用学习微服务passjava-study的方法
passjava-member和passjava-study项目的pom文件引入openfeign依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
返回某个用户学习题目的总时长
@RequestMapping("/member/list/test") public R memberStudyTimeTest() { StudyTimeEntity studyTimeEntity = new StudyTimeEntity(); studyTimeEntity.setTotalTime(100); // 学习时长:100分钟 studyTimeEntity.setQuesTypeId(1L); // 题目类型:1 (javaBasic) return R.ok().put("studyTime", Arrays.asList(studyTimeEntity)); }
创建package: com.jackson0714.passjava.member.feign
创建StudyTimeFeignService接口
添加注解@FeignClient
。显示声明这个接口用来远程调用study
服务。
@FeignClient("passjava-study") public interface StudyTimeFeignService {}
添加远程调用方法
public R memberStudyTime();
给方法添加要远程调用的方法的路径study/studytime/member/list/test
@RequestMapping("study/studytime/member/list/test") public R getMemberStudyTimeListTest();
添加注解@EnableFeignClients
开启远程调用服务。
给类PassjavaStudyApplication.java添加注解@EnableFeignClients
。
basePackages代表自动扫码指定路径下所有带有@FeignClient注解的接口。
@EnableFeignClients(basePackages = "com.jackson0714.passjava.member.feign") @EnableDiscoveryClient @MapperScan("com.jackson0714.passjava.member.dao") @SpringBootApplication public class PassjavaMemberApplication { public static void main(String[] args) { SpringApplication.run(PassjavaMemberApplication.class, args); } }
测试接口
启动passjava-member和passjava-study服务
用postman工具或浏览器输入请求地址
返回结果如下图
studytime和member都有数据,学习时长:100分钟,昵称:悟空聊架构
示例:用户id作为参数在服务间传递
MemberController
@RequestMapping("/studytime/list/test/{id}") public R getMemberStudyTimeListTest(@PathVariable("id") Long id) { //mock数据库查到的会员信息 MemberEntity memberEntity = new MemberEntity(); memberEntity.setId(id); // 学习时长:100分钟 memberEntity.setNickname("悟空聊架构"); //远程调用拿到该用户的学习时长(学习时长是mock数据) R memberStudyTimeList = studyTimeFeignService.getMemberStudyTimeListTest(id); return R.ok().put("member", memberEntity).put("studytime", memberStudyTimeList.get("studytime")); }
StudyTimeFeignService
@FeignClient("passjava-study") public interface StudyTimeFeignService { @RequestMapping("study/studytime/member/list/test/{id}") public R getMemberStudyTimeListTest(@PathVariable("id") Long id); }
StudyTimeController
@RequestMapping("/member/list/test/{id}") public R memberStudyTimeTest(@PathVariable("id") Long id) { StudyTimeEntity studyTimeEntity = new StudyTimeEntity(); studyTimeEntity.setTotalTime(100); // 学习时长:100分钟 studyTimeEntity.setQuesTypeId(1L); // 题目类型:1 (javaBasic) return R.ok().put("studytime", Arrays.asList(studyTimeEntity)); }
@FeignClient
),声明这个接口类是用来远程调用其他服务的@EnableFeignClients
)https://github.com/Jackson0714/PassJava-Platform