springcloud 基础部分:创建项目
一、基本环境
参考:
1、B站尚硅谷视频:https://www.bilibili.com/video/BV18E411x7eT
2、笔记:https://blog.csdn.net/qq_36903261/category_10087946.html
二、创建父项目
1、选择maven项目
![](https://img2022.cnblogs.com/blog/672778/202207/672778-20220710195831640-67467401.png)
2、填写项目信息
3、选择本地maven
三、环境配置
1、添加自动引入
2、设置字符编码 UTF-8
3、 工程目录显示的文件过滤
4、java编译版本选择
5、注解生效激活
四、父工程POM文件
<!--统一管理jar包版本--> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.12</junit.version> <lombok.version>1.18.10</lombok.version> <log4j.version>1.2.17</log4j.version> <mysql.version>8.0.18</mysql.version> <druid.version>1.1.20</druid.version> <mybatis.spring.boot.version>1.3.2</mybatis.spring.boot.version> </properties> <!--子模块继承之后,提供作用:锁定版本+子module不用写groupId和version--> <dependencyManagement> <dependencies> <!--spring boot 2.2.2--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.2.2.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <!--spring cloud Hoxton.SR1--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR1</version> <type>pom</type> <scope>import</scope> </dependency> <!--spring cloud alibaba--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2.1.0.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> <scope>runtime</scope> </dependency> <!-- druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${druid.version}</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.spring.boot.version}</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <!--log4j--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> <addResources>true</addResources> </configuration> </plugin> </plugins> </build> </project>
错误处理:Plugin ‘org.springframework.boot:spring-boot-maven-plugin:‘ not found
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.2.2.RELEASE</version> <!-- 添加版本号,和springboot保持一致 --> </plugin>
// 重启idea环境后生效
五、maven测试验证
1、选中maven生命周期,执行,测试是否正常。
2、关闭test环节。
六、创建子模块
2、选择jdk环境
3、填写模块名称
4、在POM添加依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.20</version> <!--子工程写了版本号,就使用子工程的版本号,如果没写版本,找父工程中规定的版本号--> </dependency> <!--mysql-connector-java--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--jdbc--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--热部署--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
5、写yml
在resources目录下新建application.yml配置文件
#微服务建议一定要写服务端口号和微服务名称 server: #端口号 port: 8081 spring: application: #微服务名称 name: cloud-payment-service #数据库配置 datasource: type: com.alibaba.druid.pool.DruidDataSource #mysql5.x的没有cj driver-class-name: com.mysql.cj.jdbc.Driver #记得先创建数据库 url: jdbc:mysql://192.168.1.138:3306/testdb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT username: root password: 123456 #mybatis配置 mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.hr.springcloud.entities #所有Entity别名类所在包
6、主启动
在java包下创建主启动类com.hr.springcloud.PaymentMain8081
@SpringBootApplication public class PaymentMain8081 { public static void main(String[] args) { SpringApplication.run(PaymentMain8081.class, args); } }
七、子模块业务类
1、建表SQL
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; INSERT INTO payment(`serial`)VALUES("张三");
2、entities
在springcloud包下新建实体类entities.Payment
//这三个注解是lombok的,除了导入依赖,idea还需要安装插件(具体操作问度娘) @Data //set/get方法 @AllArgsConstructor //有参构造器 @NoArgsConstructor //无参构造器 public class Payment implements Serializable { private long id; private String serial; }
在entities包下新建CommonResult(json封装体,传给前端的)
//返回给前端的通用json数据串 @Data //set/get方法 @AllArgsConstructor //有参构造器 @NoArgsConstructor //无参构造器 public class CommonResult<T> { private Integer code; private String message; private T data; //泛型,对应类型的json数据 //自定义两个参数的构造方法 public CommonResult(Integer code, String message){ this(code, message, null); } }
3、dao
在springcloud包下新建dao.PaymentDao接口
@Mapper public interface PaymentDao { //增 int create(Payment payment); //改 加上@Param注解,mapper中就可以采用#{}的方式把@Param注解括号内的参数进行引用 Payment getPaymentById(@Param("id") Long id); //这里用增和改进行演示,有兴趣的可以自己加其他的方法 }
4、mapper
在resources目录下新建mapper/PaymentMapper.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="com.hr.springcloud.dao.PaymentDao"> <resultMap id="BaseResultMap" type="com.hr.springcloud.entities.Payment"> <id column="id" property="id" jdbcType="BIGINT"/> <id column="serial" property="serial" jdbcType="VARCHAR"/> </resultMap> <!-- 增 --> <!-- Payment标红了不用管,因为我们已经在yml文件中指定了Payment的位置了 --> <insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id"> insert into payment(serial) values(#{serial}); </insert> <!-- 改 --> <!--返回用resultMap,防止命名不规范--> <select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap"> select * from payment where id=#{id}; </select> </mapper>
5、service
在springcloud包下新建service.PaymentService接口
public interface PaymentService { int create(Payment payment); Payment getPaymentById(@Param("id") Long id); }
在service包下新建impl.PaymentServiceIpml实现类
@Service public class PaymentServiceIpml implements PaymentService { @Resource //@Autowired也可以 private PaymentDao paymentDao; public int create(Payment payment){ return paymentDao.create(payment); } public Payment getPaymentById(Long id){ return paymentDao.getPaymentById(id); } }
6、controller
在springcloud包下新建controller.PaymentController
@RestController @Slf4j //日志 public class PaymentController { @Resource private PaymentService paymentService; //前后端分离,所以不能直接返回对象,数据要先经过CommonResult封装再返回 @PostMapping("/payment/create") public CommonResult create(@RequestBody Payment payment){ int result = paymentService.create(payment); log.info("******插入的数据为:" + payment); log.info("******插入结果:" + result); if(result > 0){ //插入成功 return new CommonResult(200, "插入数据库成功", result); }else{ return new CommonResult(444, "插入数据库失败"); } } @GetMapping("/payment/get/{id}") public CommonResult getPaymentById(@PathVariable("id") Long id){ Payment payment = paymentService.getPaymentById(id); log.info("******查询结果:" + payment); if(payment != null){ //查询成功 return new CommonResult(200, "查询成功", payment); }else{ return new CommonResult(444, "没有对应记录,查询ID:" + id); } } }
错误处理:...class not find
PaymentMapper.xml、application.yml 检查路径名是否正确。
八、子模块运行测试
1、启动项目
2、浏览器输入http://localhost:8081/payment/get/1
,查询成功。
3、使用postman工具,输入 http://localhost:8081/payment/create,发送post请求进行测试
// 注意:参数传递写在Body中,写在Params中会报错400
九、消费者子模块
1、新建模块
// 参照子模块创建步骤
2、改POM
往pom中添加:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!--热部署--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
3、写yml
在resources目录下新建application.yml文件
#访问一个网站时,默认是80端口,给用户80端口,用户就可以不用加端口直接访问页面 server: port: 8082
4、主启动
com.hr.springcloud.OrderMain8082
@SpringBootApplication public class OrderMain8082 { public static void main(String[] args) { SpringApplication.run(OrderMain8082.class, args); } }
十、消费者模块业务类
1、复制cloud-provider-payment8081项目里的entities(里面2个实体类)到本项目(cloud-consumer-order8082)的springcloud包下。(在后面的工程重构,会把实体类抽取出来)
2、在springcloud包下新建config.ApplicationContextConfig
@Configuration public class ApplicationContextConfig { //往容器中添加一个RestTemplate //RestTemplate提供了多种便捷访问远程http访问的方法 @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } }
3、在springcloud包下新建controller.OrderController
@RestController @Slf4j public class OrderController { public static final String PAYMENT_URL = "http://localhost:8081"; @Resource private RestTemplate restTemplate; //因为浏览器只支持get请求,为了方便这里就用get @GetMapping("/consumer/payment/create") public CommonResult<Payment> create(Payment payment){ log.info("********插入的数据:" + payment); //postForObject分别有三个参数:请求地址,请求参数,返回的对象类型 return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class); } @GetMapping("/consumer/payment/get/{id}") public CommonResult<Payment> getPayment(@PathVariable("id") Long id){ log.info("********查询的id:" + id); //getForObject两个参数:请求地址,返回的对象类型 return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class); } }
十一、服务者、消费者整合测试
启动两个项目进行测试,两个项目都启动后,右下角会弹出个services提示,点击show,运行的项目合并在一起显示:
在浏览器中输入http://localhost:8082/consumer/payment/get/1成功查询到数据。
在浏览器中输入 http://localhost:8082/consumer/payment/create?serial=钱七 插入一条数据。
// 备注:消费者模块,插入数据的controller采用了get方式提交,因此才能用浏览器直接验证。
十一、工程重构
目的:对系统重复部分进行重构,提取公共模块。
1、新建模块:cloud-api-commons
2、改pom
添加依赖:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- 一个Java工具包 --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.1.0</version> </dependency> </dependencies>
3、拷贝entities到本项目中(路径需要一样:com.hr.springcloud)
4、对项目进行打包
5、删除另外两个项目的entities包
6、给两个项目引入打包后项目的坐标
<!-- 引用自己定义的api通用包 --> <dependency> <groupId>com.hr.springcloud</groupId> <artifactId>cloud-api-commons</artifactId> <version>${project.version}</version> </dependency>
7、重新测试
查询:http://localhost:8082/consumer/payment/get/1
新增:http://localhost:8082/consumer/payment/create?serial=赵六
十二、常见错误
1、错误:The server time zone value 'EDT' is unrecognized or represents more than one time zone.
// 解决:参照linux、linux安装配置文档,修改mysql系统时间
2、报错:java: 程序包lombok不存在
// idea设置:File->Settings->builder->maven->Runner->Delegate IDE build/run actions to Maven勾上,然后重启idea
3、配置services 只能显示5个运行项目的限制