微服务模块构建流程

建module 改pom 改yml 主启动 业务类
建数据库 建entities 建dao 加service 加controller

Devtools

热部署,更新内容后自动重新启动

  1. 添加jar包(放在子包中)

    1
    2
    3
    4
    5
    6
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
    </dependency>
  2. 添加插件(放入父类总工程)

    1
    2
    3
    4
    5
    6
    7
    8
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
    <!-- <fork>true</fork>-->
    <addResources>true</addResources>
    </configuration>
    </plugin>
  3. 开启自动编译的选项

  4. ctrl+shirft+alt+/

RestTemplate

RestTemplate提供了多种编写访问Http服务的方法,
是一种简单便携的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集。
与之类似的还有spring-database-template。redis-template

  1. 配置bean

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @Configuration
    open class ApplicationContextConfig {

    private val gsonHttpMessageConverter = GsonHttpMessageConverter()

    //这里的原因是因为kotlin的反序列化有点难搞,你需要配置他的转换器为gson的转换器。
    @Bean
    open fun restTemplate() = RestTemplate().apply {
    messageConverters.add(0,gsonHttpMessageConverter)
    }
    }
    //applicationContext.xml <bean id="" class="">

    这样子,每次spring都会为你自动配置一个restTemplate。

  2. 使用Resttemplate

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    @RestController
    @RequestMapping("/consumer")
    class OrderController {

    private val PAYMENT_URL = "http://localhost:8001"
    private val log = LoggerFactory.getLogger(javaClass)

    @Resource
    private lateinit var restTemplate: RestTemplate

    @GetMapping("/payment/create")
    fun create(payment: Payment): CommonResult<*> {
    log.info("消费者创建订单:$payment")
    return restTemplate.postForObject("$PAYMENT_URL/payment/create", payment)
    }

    @GetMapping("/payment/get/{id}")
    fun getPayment(@PathVariable("id") id: Long): CommonResult<*> {
    log.info("消费者查询订单")
    return restTemplate.getForObject<CommonResult<Payment>>("$PAYMENT_URL/payment/get/$id")

    }
    }

    他的主要方法就是get或者postForObject。然后三个参数分别为地址,请求参数和返回值

工程同构

为了解决一些冗余问题,如:

这些entities类都是一模一样的
工程同构操作如下:

  1. 建一个module
    命名为cloud-api-commons
    然后导入以下依赖(因为以后要用):
    1
    2
    3
    4
    5
    6
    7
    <dependencies>
    <dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.15</version>
    </dependency>
    </dependencies>
    然后把其他类中所有的entities都复制粘贴过来。
  2. maven install
    然后调用maven的安装。
  3. 最后在需要使用的子module中引入这个jar包

    就算实现了工程同构了