1、整体思路:
通过Nacos进行服务发现(服务注册中心),再通过Feign进行服务调用(远程服务调用),即可实现不同服务之间的调用。
2、Nacos服务注册
- 在需要调用的微服务模块的父模块进行统一引入依赖(或者分别引入依赖)
<!--服务注册-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
- 配置application.properties,注册Nacos服务的配置信息
# nacos服务地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
- 在服务模块的启动类上进行注解添加
@EnableDiscoveryClient
- 重启模块,启动注册中心,查看
有显示则表明注册成功~
3、Feigen服务调用
假设现在有需求,删除小节的同时也删除阿里云上的存储的视频。(即service-edu调用service-vod里的方法。)
- 添加pom依赖(父模块或本模块)
<!--服务调用-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 在调用端的启动类添加注解,即service-edu。
@EnableFeignClients
- 在调用端创建接口
//服务调用注解,指定被调用端服务名称
@FeignClient("service-vod")
//添加组件注解,交给spring管理
@Component
public interface VodClient {
//service-vod下的要调用的方法
//注:路径写全!and @PathVariable注解要指定名称
@DeleteMapping("/eduvod/video/{id}")
public R removeVideo(@PathVariable("id") String id);
}
- 调用端进行调用
@Autowired
private VodClient vodClient
//删除小节同时删除视频
public void removeVideoById(String videoInfoId) {
//根据小节id查询小节对象
EduVideo eduVideo = baseMapper.selectById(videoInfoId);
//获取小节对象中的视频源idrere
String videoSourceId = eduVideo.getVideoSourceId();
//若视频源id存在,则调用service-vod中的方法
if(!StringUtils.isEmpty(videoSourceId)){
vodClient.removeVideo(videoSourceId);
}
baseMapper.deleteById(videoInfoId);
}