学习时的所有代码都上传到了GitHub和gitee了:
GitHub:https://github.com/angenin/cloud2020
gitee:https://gitee.com/angenin/cloud2020
springcloud官方文档(Hoxton SR5):https://cloud.spring.io/spring-cloud-static/Hoxton.SR5/reference/htmlsingle/
springcloud中文文档:https://www.springcloud.cc/
springcloud中国社区文档:http://docs.springcloud.cn/
https://www.bookstack.cn/read/spring-cloud-docs/docs-index.md
官方对应关系:http://start.spring.io/actuator/info
编程风格:约定 > 配置 > 编码
删除src目录,并在pom中添加
<packaging>pompackaging>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<junit.version>4.12junit.version>
<lombok.version>1.18.10lombok.version>
<log4j.version>1.2.17log4j.version>
<mysql.version>8.0.18mysql.version>
<druid.version>1.1.20druid.version>
<mybatis.spring.boot.version>1.3.2mybatis.spring.boot.version>
properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-dependenciesartifactId>
<version>2.2.2.RELEASEversion>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>Hoxton.SR1version>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-alibaba-dependenciesartifactId>
<version>2.1.0.RELEASEversion>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>${druid.version}version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>${mybatis.spring.boot.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>${junit.version}version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
dependencies>
dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<fork>truefork>
<addResources>trueaddResources>
configuration>
plugin>
plugins>
build>
project>
maven中dependencyManagement标签:
子项目中,如果不指定,默认和父项目dependencyManagement标签中的版本一致,并且父项目dependencyManagement标签只是规定了版本号,具体引入依赖还是子项目引入。
maven中跳过单元测试
父工程创建完成后执行mvn:install
将父工程发布到仓库方便子工程继承。
子项目名:cloud-provider-payment8001
调整一下父项目pom文件
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.20version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
在resources目录下新建application.yml配置文件
#微服务建议一定要写服务端口号和微服务名称
server:
#端口号
port: 8001
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://localhost:3306/db2020?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
#mybatis配置
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.angenin.springcloud.entities #所有Entity别名类所在包
在java包下创建主启动类com.angenin.springcloud.PaymentMain8001
@SpringBootApplication
public class PaymentMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8001.class, args);
}
}
建表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("张三");
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);
}
}
dao
在springcloud包下新建Dao.PaymentDao接口
@Mapper
public interface PaymentDao {
//增
int create(Payment payment);
//改 加上@Param注解,mapper中就可以采用#{}的方式把@Param注解括号内的参数进行引用
Payment getPaymentById(@Param("id") Long id);
//这里用增和改进行演示,有兴趣的可以自己加其他的方法
}
mapper
在resources目录下新建mapper目录,然后新建PaymentMapper.xml
<mapper namespace="com.angenin.springcloud.Dao.PaymentDao">
<resultMap id="BaseResultMap" type="com.angenin.springcloud.entities.Payment">
<id column="id" property="id" jdbcType="BIGINT"/>
<id column="serial" property="serial" jdbcType="VARCHAR"/>
resultMap>
<insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
insert into payment(serial)values(#{serial});
insert>
<select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap">
select * from payment where id=#{id};
select>
mapper>
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);
}
}
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);
}
}
}
启动项目
浏览器输入http://localhost:8001/payment/get/1
,查询成功。
因为浏览器一般不支持直接发送post请求,所以,需要使用工具进行测试。(我这里用的是Postman)
重新测试查询,没问题。
输入http://localhost:8001/payment/create
发送post请求,往数据库中插入一条数据,需要把数据写到body中。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<fork>truefork>
<addResources>trueaddResources>
configuration>
plugin>
plugins>
build>
Shift+Ctrl+Alt+/
(Mac系统的把Ctrl换成command键),选中Registry…往pom中添加:
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
project>
在resources目录下新建application.yml文件
#访问一个网站时,默认是80端口,给用户80端口,用户就可以不用加端口直接访问页面
server:
port: 80
com.angenin.springcloud.OrderMain80
@SpringBootApplication
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class, args);
}
}
复制cloud-provider-payment8001项目里的entities(里面2个实体类)到本项目(cloud-consumer-order80)的springcloud包下。(在后面的工程重构,阳哥会把实体类抽取出来)
在springcloud包下新建config.ApplicationContextConfig
@Configuration
public class ApplicationContextConfig {
//往容器中添加一个RestTemplate
//RestTemplate提供了多种便捷访问远程http访问的方法
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
在springcloud包下新建controller.OrderController
@RestController
@Slf4j
public class OrderController {
public static final String PAYMENT_URL = "http://localhost:8001";
@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/consumer/payment/get/1
成功查询到数据。
在浏览器中输入http://localhost/consumer/payment/create?serial=王五
插入一条数据。
观察问题:系统中有重复部分,重构。
添加依赖:
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.1.0version>
dependency>
dependencies>
<dependency>
<groupId>com.angenin.springcloudgroupId>
<artifactId>cloud-api-commonsartifactId>
<version>${project.version}version>
dependency>
下一篇笔记:SpringCloud入门学习笔记(5-7初级部分,注册中心【Eureka、Zookeeper和Consul】)
学习视频(p1-p14):https://www.bilibili.com/video/BV18E411x7eT?p=1