# Re:0 - Starting Life in Backend - Day8

seal

总有一条蜿蜒在童话镇里七彩的河
沾染魔法的乖张气息
却又在爱里曲折
川流不息扬起水花
又卷入一帘时光入水
让所有很久很久以前
都走到幸福结局的时刻

Microservice-Level 1: Creating parent services and child services

Target: Use Spring Cloud create a parent service, then create child services to inherits the parent service

Create Parent Service

Just create the project is ok, I perfer to use Spring Initializer to build

Create Child Services

I need to create Order model and Stock model


Stock

Controller:

package com.seal.stock.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/stock")
public class StockController {

    @RequestMapping("/reduct")
    public String reduct() {
        return "reduct";
    }
}

An easy controller, return reduct when triggered.

Order

Controller

package com.seal.order.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/add")
    public String add() {
        String msg = restTemplate.getForObject("http://localhost:8102/stock/reduct", String.class);
        return "add\n"+msg;
    }
}

Add RestTemplate to achieve the target of socket

main

package com.seal.order;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
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);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        RestTemplate restTemplate = builder.build();
        return restTemplate;
    }
}

Use @Bean here to initialize RestTemplate


Port

remember to change port child services uses, avoid re-used.