微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SpringCloud学习笔记(二) 提供者和消费者

创建提供者子模块

建module

选择新建module

img

不选择任何模板直接创建maven模块

image-20211002142202088

image-20211002142414492

最终目录结构如下

image-20211002142510606

改pom.xml

新建模块后,父工程的pom文件自动引入<modole>标签,这时需要将<packaging>标签移到<module>标签之上

image-20211002142633180

之后为子模块添加依赖

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/MysqL/mysql-connector-java -->
    <dependency>
        <groupId>MysqL</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

写yml

在子工程的资源文件夹下新建yml配置文件

image-20211002143557113

image-20211002143623605

在application.yml中添加如下配置

server:
  port: 8001


spring:
  application:
    name: cloud-payment-service
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource # 数据源操作类型
    driver-class-name: org.gjt.mm.MysqL.Driver # 数据库驱动
    url: jdbc:MysqL://localhost:3306/sp?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 12345

mybatis:
  mapperLocations: classpath:mapper/*.xml
  type-aliases-package: zjc.entities # Entity所在包

配置主启动类

image-20211002144311679

新建一个类作为主启动类

代码如下

package zjc;

import org.springframework.boot.SpringApplication;

@SpringBootApplication // 标记这个类是主启动类
public class PaymentMain8001 {
	public static void main(String[] args) {
		SpringApplication.run(PaymentMain8001.class, args);
	}
}

写业务类

  1. MysqL建表

    CREATE TABLE payment (
     id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT ID,
     'serial' VARCHAR(200) DEFAULT,
     PRIMARY KEY(id)
    ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
    
  2. 建entities

    新建如下model类

    package zjc.entities;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.io.Serializable;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Payment implements Serializable {
    	private Long id;
    	private String serial;
    }
    
  3. 新建返回结果类

    这个类一般会单独提取一个模块中,步骤后续再说

    package zjc.common;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Result {
    	private Integer code;
    	private String message;
    	private Object data;
    	public Result(Integer code, String message) {
    		this(code, message, null);
    	}
    }
    
  4. 书写dao接口

    package zjc.dao;
    
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import zjc.entities.Payment;
    
    @Mapper
    public interface PaymentDao {
    	public int create(Payment payment);
    	public Payment getPaymentById(@Param("id") Long id);
    }
    
  5. 配置Mapper

    在资源文件夹下新建mapper文件夹,以后的Mapper.xml配置文件都会放到这里面

    image-20211002150528397

    Mapper.xml认配置如下

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="DAO对应的类">
    
    </mapper>
    

    根据之前写的dao接口在<mapper>标签中配置响应的sql

    <insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
        insert into payment(serial) values(#{serial})
    </insert>
    
    <!--为了防止驼峰命名冲突,建议使用结果集映射-->
    <resultMap id="BaseResultMap" type="zjc.entities.Payment">
        <!--字段一一映射-->
        <id column="id" property="id" jdbcType="BIGINT"/>
        <id column="serial" property="serial" jdbcType="VARCHAR"/>
    </resultMap>
    <select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap">
        select `id`,`serial` from payment where  id=#{id}
    </select>
    
  6. 创建service

    根据dao创建相应的service接口

    package zjc.service;
    
    import org.apache.ibatis.annotations.Param;
    import org.springframework.stereotype.Service;
    import zjc.entities.Payment;
    
    public interface PaymentService {
    	public int create(Payment payment);
    	public Payment getPaymentById(@Param("id") Long id);
    }
    

    以及service接口的实现类

    springcloud中推荐使用Resource注解进行注入

    package zjc.service.impl;
    
    import org.springframework.stereotype.Service;
    import zjc.dao.PaymentDao;
    import zjc.entities.Payment;
    import zjc.service.PaymentService;
    
    import javax.annotation.Resource;
    
    @Service
    public class PaymentServiceImpl implements PaymentService {
    	@Resource
    	private PaymentDao paymentDao;
    	
    	@Override
    	public int create(Payment payment) {
    		return paymentDao.create(payment);
    	}
    
    	@Override
    	public Payment getPaymentById(Long id) {
    		return paymentDao.getPaymentById(id);
    	}
    }
    
  7. 运行项目,访问网页获取结果集

    访问localhost:8001/payment/get/3

    获取以下结果

    image-20211002155707962

    对于method为post的请求,浏览器对get以外的访问方式支持较差,因此使用postman、swagger或者apifox等api调试工具

    使用post方式访问localhost:8001/payment/create?serial=111

    image-20211002160059151

    获取以下结果

    {
        "code": 200,
        "message": "数据插入成功",
        "data": 1
    }
    

提取常用类到子模块

有一些常用的类如果每一个模块都单独创建无疑会增加代码冗余度

为了增强代码复用性可以将这些类单独提取一个模块中

  1. 创建一个子模块

  2. 配置其pom文件

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.1.0</version>
    </dependency>
    
  3. 将常用的类copy到这个模块中

image-20211002165203689

之后将CommonComponent模块使用mvc:install打包就可以在其他子模块中引入了

image-20211002170802199

在其它模块中添加CommonComponent的依赖

<dependency>
    <groupId>zjc</groupId>
    <artifactId>CommonComponent</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

创建消费者子模块

创建多个子模块时可能会出现如下提醒,点击Use Services可以进入Services面板可以更好的处理多个模块

image-20211002164809473

创建新模块后别忘了引入CommonComponent模块的相关依赖

  1. 创建新模块并编辑其springboot配置文件

    image-20211002164018359

    server:
    	port: 80 # 将消费者模块的启动端口设置为80
    
  2. 配置config

    package zjc.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.client.RestTemplate;
    
    @Configuration
    public class ApplicationContextConfig {
    
    	@Bean // 注入restTemplate
    	public RestTemplate getRestTemplate() {
    		return new RestTemplate();
    	}
    }
    
    
  3. 使用restTemplate访问restful接口

    restTemplate的三个参数urlresultMap, ResponseBean.class分别到表Rest请求地址、请求参数和HTTP响应转换的对象类型

    创建消费者的controller

    因为用户是用浏览器访问,所以Mapping是用@GetMapping注解

    package zjc.controller;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    import zjc.common.Result;
    import zjc.entities.Payment;
    
    import javax.annotation.Resource;
    
    @Slf4j
    @RestController
    public class OrderController {
    	public static final String PAYMENT_URL = "http://localhost:8001";
    
    	@Resource
    	private RestTemplate restTemplate;
    
    	@GetMapping("consumer/payment/create")
    	public Result create(Payment payment) {
    		return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, Result.class);
    	}
    
    	@GetMapping("/consumer/payment/get/{id}")
    	public Result create(@PathVariable("id") Long id) {
    		return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, Result.class);
    	}
    }
    
    
  4. 启动项目并访问

    先启动提供者再启动消费者

    之后访问localhost/consumer/payment/get/3

    访问结果如下

    image-20211002173147426

    再访问localhost/consumer/payment/create/?serial=safaffyug

    访问结果如下

    image-20211002173406080


热部署

推荐使用jrebel来进行热部署

在setting中的plugins中安装jrebel插件

然后进行激活

在线GUID地址

服务器地址:https://jrebel.qekang.com/{GUID}

激活会用到服务器地址

在激活面板中的Team URL中填入上面获取到的服务器地址

之后再填写自己的邮箱完成激活

激活jrebel后进行以下设置

image-20211002161934551

image-20211002162031760

按快捷键 Ctrl+Shift+Alt+/ ,选择 Registry

image-20211002162116350

image-20211002162140781

设置后之后就可以使用jrebel热部署项目了

点击左下角的jrebel panel

勾选需要热部署的项目

image-20211002162300503

Jrebel会自动生成rebel.xml配置文件

image-20211002162323859

运行项目时只需要点击右上角的小火箭即可用jrebel热部署项目

image-20211002162433257

修改项目后,只需要使用Ctrl + Shift + F9就能实现修改效果

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐