Spring Cloud全文目录
源码
什么是微服务?有手就行
SpringCloud简介与5大常用组件
一、手把手教你搭建SpringCloud项目(一)搭建Maven父工程,傻瓜式操作
二、手把手教你搭建SpringCloud项目(二)生产者与消费者
三、手把手教你搭建SpringCloud项目(三)集成Eureka服务注册中心
四、手把手教你搭建SpringCloud项目(四)EurekaServer集群版搭建
五、手把手教你搭建SpringCloud项目(五)生产者集群版搭建
六、手把手教你搭建SpringCloud项目(六)actuator微服务信息完善与Eureka自我保护机制
七、手把手教你搭建SpringCloud项目(七)Eureka实现服务发现(Discovery)
八、手把手教你搭建SpringCloud项目(八)集成Consul服务注册中心
九、手把手教你搭建SpringCloud项目(九)集成Ribbon负载均衡器
十、手把手教你搭建SpringCloud项目(十)集成OpenFeign服务接口调用
十一、手把手教你搭建SpringCloud项目(十一)集成Hystrix之服务降级
十二、手把手教你搭建SpringCloud项目(十二)集成Hystrix之服务熔断
十三、手把手教你搭建SpringCloud项目(十三)集成Hystrix之图形化Dashboard实时监控
十四、手把手教你搭建SpringCloud项目(十四)集成Gateway新一代服务网关
十五、手把手教你搭建SpringCloud项目(十五)集成Config分布式配置中心
十六、手把手教你搭建SpringCloud项目(十六)集成Bus消息总线
十七、手把手教你搭建SpringCloud项目(十七)集成Stream消息驱动
十八、手把手教你搭建SpringCloud项目(十八)集成Sleuth分布式链路跟踪
我们继续上一篇的文章,上一篇文章将Maven父工程微服务搭建完成了,这篇文章我们将继续搭建,搭建生产者和消费者,生产者我们可以这样理解就是我们的服务端,就是我们使用代码写的业务逻辑接口,而消费者就是我们用户,用户通过app或者web调用我们服务端的接口,获取信息。那我们下面就直接搭建,从项目中进行了解学习。
搭建生产者微服务模块
步骤:
- 建module
- 改pom
- 写yml
- 主启动
- 业务类
1.建立生产者支付module: springcloud-provider-payment8001
项目结构:
2.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud</artifactId>
<groupId>com.dyh.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-provider-payment8001</artifactId>
<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.10</version>
</dependency>
<!--mysql-connector-java-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<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>
</project>
3.application.yml
server:
port: 8001
spring:
application:
name: springcloud-payment-service
datasource:
type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
driver-class-name: org.gjt.mm.mysql.Driver #mysql驱动包
url: jdbc:mysql://localhost:3306/db2021?useUnicode=true&characterEncoding-utr-8&useSSL=false
username: root
password: 123456
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.dyh.springcloud.entities #所有Entity别名类所在包
4.主启动类 PaymentMain8001
package com.dyh.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PaymentMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8001.class,args);
}
}
5. 业务类
建库
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
Payment
package com.dyh.springcloud.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;
}
CommentResult
//Json封装体CommentResult,传给前端,判断编码是否成功,成功才显示
package com.dyh.springcloud.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> { //泛型:如果装的payment 返回payment,装的order 返回order
private Integer code;
private String message;
private T data;
public CommonResult(Integer code,String message){
this(code,message,null);
}
}
PaymentDao
package com.dyh.springcloud.dao;
import com.dyh.springcloud.entities.Payment;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface PaymentDao {
int create(Payment payment);
Payment getPaymentById(@Param("id") Long id);
}
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="com.dyh.springcloud.dao.PaymentDao">
<insert id="create" parameterType="com.dyh.springcloud.entities.Payment" useGeneratedKeys="true" keyProperty="id">
insert into payment(serial) values(#{serial})
</insert>
<resultMap id="BaseResultMap" type="com.dyh.springcloud.entities.Payment">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="serial" property="serial" jdbcType="VARCHAR"/>
</resultMap>
<select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap">
select * from payment where id=#{id};
</select>
</mapper>
PaymentService
package com.dyh.springcloud.service;
import com.dyh.springcloud.entities.Payment;
import org.apache.ibatis.annotations.Param;
public interface PaymentService {
public int create(Payment payment);
public Payment getPaymentById(@Param("id") Long id);
}
PaymentServiceImpl
package com.dyh.springcloud.service;
import com.dyh.springcloud.dao.PaymentDao;
import com.dyh.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PaymentServiceImpl implements PaymentService{
@Autowired
private PaymentDao paymentDao;
@Override
public int create(Payment payment){
return paymentDao.create(payment);
}
@Override
public Payment getPaymentById(Long id){
return paymentDao.getPaymentById(id);
}
}
PaymentController
package com.dyh.springcloud.controller;
import com.dyh.springcloud.entities.CommonResult;
import com.dyh.springcloud.entities.Payment;
import com.dyh.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@Slf4j
public class PaymentController {
@Autowired
private PaymentService paymentService;
//只传给前端CommonResult,不需要前端了解其他的组件
@PostMapping(value = "/payment/create")
public CommonResult create(@RequestBody Payment payment){
int result = paymentService.create(payment);
log.info("*****插入结果:"+result);
if(result > 0){
return new CommonResult(200,"插入数据成功",result);
}else{
return new CommonResult(444,"插入数据失败",null);
}
}
@GetMapping(value = "/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,null);
}
}
}
6.启动8001服务,测试
Chrom浏览器可能不支持Post请求,可以使用PostMan工具测试
搭建消费者微服务模块
步骤:
- 建module
- 改pom
- 写yml
- 主启动
- 业务类
1.建立消费者订单module: springcloud-consumer-order81
2.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud</artifactId>
<groupId>com.dyh.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-consumer-order81</artifactId>
<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.application.yml
server:
port: 81
spring:
application:
name: springcloud-order-server
4.主启动类 OrderMain81
package com.dyh.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OrderMain81 {
public static void main(String[] args) {
SpringApplication.run(OrderMain81.class,args);
}
}
5.业务类
订单也需要Payment、CommonResult实体类,但是不需要操作数据库,没有Service、Dao,只需添加Controller即可。
Payment
package com.dyh.springcloud.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;
}
CommentResult
//Json封装体CommentResult,传给前端,判断编码是否成功,成功才显示
package com.dyh.springcloud.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> { //泛型:如果装的payment 返回payment,装的order 返回order
private Integer code;
private String message;
private T data;
public CommonResult(Integer code,String message){
this(code,message,null);
}
}
RestTemplate
RestTemplate: RestTemplate提供了多种便捷访问远程Http服务的方法,是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集,实现81到8001的远程调用。
官网地址:
https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
使用:
使用restTemplate访问restful接口非常的简单粗暴,(url、requestMap、ResponseBean.class)这三个参数分别代表REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。
将RestTemplate对象注册到容器中
package com.dyh.springcloud.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
OrderController
package com.dyh.springcloud.controller;
import com.dyh.springcloud.entities.CommonResult;
import com.dyh.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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;
@RestController
@Slf4j
public class OrderController {
private static final String PAYMENT_URL="http://localhost:8001";
@Autowired
private RestTemplate restTemplate;
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment, CommonResult.class);
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
}
6.启动81、8001服务,测试
80服务调用8001服务,实现效果如下:
查询:
添加:
工程重构
项目中存在相同的代码(entities包下的Payment.class和CommonResult.class),造成代码冗余,可以进行重构。
通过Maven聚合父工程,把相同重复的代码移到公开公用的工程里面,还可以放第三方接口、工具类,统一调配使用。
建立公共module
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud</artifactId>
<groupId>com.dyh.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-api-commons</artifactId>
<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>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
</project>
将entities包复制到cloud-api-commons
删除重复entities,引入maven install的jar包坐标即可使用。
<!--引入自己定义的api通用包,可以使用Payment支付Entity-->
<dependency>
<groupId>com.dyh.springcloud</groupId>
<artifactId>springcloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
使用Maven打包发布上传到公用本地库里
打开Maven窗口,执行clean测试一下,无误后出现BUILD SUCCESS,然后执行install
到这里我们springcloud的简单的搭建就成功啦。是不是so easy!