springcloud初體驗(真香)
一、微服務簡介
Ⅰ、我對微服務的理解
微服務是軟件開發的一種架構方式,由單一的應用小程序構成的小服務;一個軟件系統由多個服務組成;在微服務中,服務是細粒度的,協議是輕量級的(部署簡單、性能開銷小)
Ⅱ、為什麼要使用微服務?
隨著時代的發展,單體架構(MVC三層模型)越來越不能滿足企業的要求;業務規模的不斷擴大、團隊開發人員的增多,使得單體架構出現瞭以下幾個問題:
(1)部署效率低(比如代碼量非常多,依賴的包非常多,那麼每一次編譯打包、部署測試的時間就會很久)
(2)團隊開發成本高(如果某個模塊出現問題,可能就要多人修改)
(3)高可用性低(打成war包部署之後,如果某一塊出現瞭問題,其他模塊都會受到影響)
(4)一旦代碼膨脹(簡單瞭說你寫的代碼量大,但功能沒實現幾個,浪費資源),上線就會變慢
SOA(面向服務編程)便出現瞭
SOA簡介
SOA是一個組件模型,它將應用程序的不同功能單元(稱為服務)進行拆分,並通過這些服務之間定義良好的接口和協議聯系起來。
雖然解決瞭服務的啟動時間,但服務化也有很大的缺點
1、耦合度較高(一個依賴可能另一個模塊,另外一個模塊又可能依賴其他模塊)
2、公司成本高(每一個模塊都要由相應的人員或者團隊維護)
2014年,隨著容器化技術的成熟以及 DevOps 文化的興起,微服務便應運而生瞭
微服務的特點
1.服務細粒度
2.協議輕量級
3.部署簡單
4.服務的獨立維護性
二、spring cloud
Ⅰ、springcloud介紹
springcloud是分佈式微服務架構的一站式解決方案,是多種微服務架構落地技術的集合體。
1.分佈式/版本化配置
2.服務註冊和發現
3.路由
4.服務到服務的通話
5.負載均衡
6.斷路器
7.全局鎖
8.領導選舉和集群狀態
9.分佈式消息傳遞
SpringCloud的官網地址:https://spring.io/projects/spring-cloud#overview
Ⅱ、boot和cloud的版本選型
1.進入springcloud官方頁面:https://spring.io/projects/spring-cloud#learn
2. LEARN->Reference Doc.
3. 版本選擇
三、springcloud初級項目體驗
最近發現網絡上很多springcloud入門體驗都是關於消費-訂單的小Demo,那我當然不能落後瞭(菜是原罪😀)
PRE: 模擬服務間調用之流程分析
1、創建一個父項目(統一管理子模塊依賴版本)
2、創建第一個子模塊—–》訂單服務模塊
3、創建第二個子模塊—–》客戶消費模塊
3.1、訂單服務模塊
編寫代碼之前應該先構思好流程,如果直接就去碼代碼,碼瞭一會可能又要添添改改;還有可能做完項目之後又要對項目進行重構,這就是沒有構思好流程。
1、技術選型
2、業務流程
3、核心業務分析
4、代碼優化
…
Ⅰ、數據庫表設計
Ⅱ、創建一個父工程
刪除多餘的文件,留下一個pom.xml文件
pom文件依賴
<?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"> <modelVersion>4.0.0</modelVersion> <groupId>com.cloud</groupId> <artifactId>springcloud_all</artifactId> <version>1.0-SNAPSHOT</version> <modules> ## 創建瞭子模塊之後會自動加入 ## <module>payment-module</module> </modules> <packaging>pom</packaging> <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.13</junit.version> <log4j.version>1.2.17</log4j.version> <lombok.version>1.16.18</lombok.version> <mysql.version>8.0.19</mysql.version> <druid.version>1.2.4</druid.version> <mybatis.spring.boot.version>2.1.4</mybatis.spring.boot.version> <druid.spring.boot.version>1.2.4</druid.spring.boot.version> <springfox-swagger-ui.version>2.9.2</springfox-swagger-ui.version> <springfox-swagger2.version>2.9.2</springfox-swagger2.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.4.3</version> <type>pom</type> <scope>import</scope> </dependency> <!-- spring-cloud 2020.0.2--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>2020.0.2</version> <type>pom</type> <scope>import</scope> </dependency> <!-- spring-cloud alibaba--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2021.1</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.spring.boot.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${druid.spring.boot.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox-swagger-ui.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox-swagger2.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>
Ⅲ、創建子訂單模塊
右鍵->New->Module
PaymentApplication啟動類
@SpringBootApplication public class PaymentApplication { public static void main(String[] args) { SpringApplication.run(PaymentApplication.class,args); } }
Ⅲ、子模塊代碼編寫
Ⅲ.Ⅰ、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_all</artifactId> <groupId>com.cloud</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.pay</groupId> <artifactId>payment-module</artifactId> <dependencies> <!-- web+監控--> <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> <!-- mybatis--> <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> </dependency> <!-- mysql--> <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> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> </dependencies> </project>
Ⅲ.Ⅱ、application.yml 配置文件編寫
server: port: 8081 spring: application: name: payment-module datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/cloud?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC username: root password: hao20001010 mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.cloud.entity
Ⅲ.Ⅲ、Controller層編寫
package com.cloud.controller; import com.cloud.Service.PaymentService; import com.cloud.entity.Payment; import com.cloud.entity.Result; import io.swagger.annotations.Api; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @author:抱著魚睡覺的喵喵 * @date:2021/4/18 * @description: */ @RestController @Slf4j @Api(value = "《----訂單模塊----》") public class PaymentController { private static final Logger logger = LoggerFactory.getLogger(PaymentController.class); @Resource private PaymentService paymentService; /** * 創建訂單模塊 * @api /payment/create * @param payment Payment實體類 * @return Result<></> */ @ApiOperation(value = "創建訂單") @PostMapping(value = "/payment/create") public Result create(@RequestBody Payment payment) { int result = paymentService.create(payment); logger.info("插入結果========》" +result); if (result > 0) { return new Result(200,"插入成功", result); } else { return new Result(500, "插入失敗", null); } } /** * 訂單查詢模塊 * @api /payment/get/{id} * @param id 編號 * @return Payment實體類 */ @GetMapping(value = "/payment/get/{id}") @ApiModelProperty(value = "訂單查詢") public Result getPaymentById(@PathVariable(value = "id") Integer id) { Payment payment = paymentService.getPaymentById(id); logger.info("訂單查詢結果=========>"+payment); if (payment != null) { return new Result(200, "查詢成功", payment); } else { logger.error("訂單插敘失敗!請排查原因"); return new Result(500, "查詢失敗,無該訂單ID:"+id, null); } } }
Ⅲ.Ⅳ、service層
public interface PaymentService { int create(Payment payment); Payment getPaymentById(@Param("id") Integer id); }
@Service public class PaymentServiceImpl implements PaymentService { @Resource private PaymentMapper paymentMapper; @Override public int create(Payment payment) { return paymentMapper.create(payment); } @Override public Payment getPaymentById(Integer id) { return paymentMapper.getPaymentById(id); } }
Ⅲ.Ⅴ、mapper層
@Mapper public interface PaymentMapper { int create(Payment payment); Payment getPaymentById(@Param("id") Integer 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.cloud.mapper.PaymentMapper"> <insert id="create" parameterType="payment" keyProperty="id" useGeneratedKeys="true"> insert into payment(orders)values(#{orders}) </insert> <select id="getPaymentById" parameterType="payment" resultMap="BaseResultMap" > select * from payment where id=#{id} </select> <resultMap id="BaseResultMap" type="payment"> <id column="id" property="id" jdbcType="INTEGER"/> <id column="orders" property="orders" jdbcType="VARCHAR"/> </resultMap> </mapper>
Ⅳ、統一結果封裝類及其實體類
@Data public class Result<T> implements Serializable { private Integer code; private String message; private T data; public Result(){} public Result(Integer code, String msg) { this(code, msg, null); } public Result(Integer code, String msg, T data) { this.code = code; this.message = msg; this.data = data; } }
@Data @AllArgsConstructor @NoArgsConstructor @ApiModel(value = "Payment實體類") public class Payment { @ApiModelProperty(value = "id") private Integer id; @ApiModelProperty(value = "訂單信息") private String orders; }
五、測試
3.2、消費服務模塊
消費模塊項目結構圖
Payment、Result以及ConsumerApplication啟動類和上面類似。
PRE:RestTemplate詳解
RestTemplate是spring封裝的一個服務端遠程HTTP請求工具,支持常見的Rest請求(get、post等)
簡單瞭說就是用來遠程調用的,因為你訂單模塊是一個服務,消費模塊又是一個單獨的服務,兩個服務端的端口號要進行交互,所以就有瞭RestTemplate
RestTemplate是服務端HTTP調用的
Jsonp是客戶端調用的
Ⅰ、消費模塊application.yml配置
server: port: 80
Ⅱ、配置類註入RestTemplate
@Configuration public class ApplicationContextConfig { @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } }
@Configuration : 該註解類似於beans
@Bean:當然就類似於bean瞭
Ⅲ、ConsumerController
@RestController @Api(value = "消費模塊") public class ConsumerController { private static final String CONSUMER_URL = "http://localhost:8081"; @Resource private RestTemplate restTemplate; @GetMapping("/consumer/payment/create") @ApiOperation(value = "模擬添加") public Result<Payment> create(Payment payment) { return restTemplate.postForObject(CONSUMER_URL + "/payment/create", payment, Result.class); } @ApiOperation(value = "模擬獲取") @GetMapping("/consumer/payment/get/{id}") public Result<Payment> getPayment(@PathVariable(value = "id") Integer id) { return restTemplate.getForObject(CONSUMER_URL + "/payment/get/" + id, Result.class); } }
3.3、全局測試
到此結束!
到此這篇關於springcloud初體驗(真香)的文章就介紹到這瞭,更多相關springcloud初體驗內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- None Found