Skip to content

微服务之间的初步调用

之前的视频模块测试数据库已经连通,现在测试从订单模块(order)来调用视频模块的接口。
将视频模块先启动起来。然后在订单模块中添加启动类:

java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
    //此处注入RestTemplate,用于网络请求使用
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

添加订单服务的Controller:

java
import com.study.pojo.Video;
import com.study.pojo.VideoOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api/v1/video_order")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/save")
    public Object save(int videoId){
        //初步的,通过网络请求访问视频服务
        Video video = restTemplate.getForObject("http://localhost:9000/api/v1/video/find_by_id?videoId=" + videoId, Video.class);
        VideoOrder videoOrder = new VideoOrder();
        videoOrder.setVideoId(videoId);
        videoOrder.setVideoTitle(video.getTitle());
        videoOrder.setCreateTime(video.getCreateTime());
        return videoOrder;
    }
}

将订单服务也启动起来,然后访问订单服务:

java
http://localhost:8000/api/v1/video_order/save?videoId=40

//访问过程
通过访问订单服务的save接口,来调用视频服务的find_by_id接口,然后查询数据库数据,返回结果。

存在的问题

  • 服务之间的IP信息写死
  • 服务之间无法提供负载均衡
  • 多个服务直接关系调用维护复杂