SpringCloud學習(二):微服務入門實戰項目搭建


 

一、開始使用Spring Cloud實戰微服務

1、SpringCloud是什么?

雲計算的解決方案?不是

SpringCloud是一個在SpringBoot的基礎上構建的一個快速構建分布式系統的工具集(全家桶)。

SpringCloud擁有SpringBoot的特點。

2、關於SpringCloud的版本?

  大部分spring軟件的版本是以:主版本.次版本.增量版本.里程碑版本的形式命名。

Spring Cloud Angel SR6???

  Angel是SpringCloud的一個大版本,Service Release6版本,標識一個bug修復的版本。

3、SpringCloud的特點?

  1)、約定優於配置

  2)、開箱即用、快速啟動

  3)、適用於各種環境(PC Server、雲環境、Subtopic、容器Docker)

  4)、輕量級的組件(如服務發現中整合的Eureka)

  5)、組件支持很豐富、功能很齊全(如提供配置中心、注冊中心、智能路由…)

  6)、選型中立(服務發現中使用Eureka、Zookeeper、Consul等都可以)

二、需要的技術儲備

  1、java(scala、Groovy…均可)

  2、構建工具

    1)、Maven

    2)、Gradle

      將maven項目轉換成gradle項目:(在pom文件的上一級目錄執行如下命令,使用cmd操作)

      gradle init --type pom

    3)、SpringBoot:http://cnblogs.com/mmzs/category/1192166.html

三、使用的軟件版本

  1、原則:使用最新的版本進行講解

  2、JDK 1.8

  3、Maven 3.3.9

  4、IDE(Spring Tool Suite 3.8.2、IDEA、Eclipse)

  5、Spring Boot

  6、SpringCloud Camden SR1

建議:大家學習時,盡量使用相同的版本進行選擇,避免采坑

SpringCloud學習(二):開始使用Spring Cloud實戰微服務

四、創建工程

1、創建調用關系的微服務

創建存在調用關系的微服務,調用關系如下

服務消費者:服務的調用方,調用別的微服務的微服務(即:依賴其他服務的服務)

服務提供者:服務的被調用方,提供API的微服務(即:為其他服務提供服務的服務)

2、編寫一個服務提供者

登陸:http://start.spring.io/

填寫信息:

(1)、將生成的maven工程導入eclipse

然后一次創建如下選中的類和配置文件。

(2)、data.sql和schema.sql

insert into user(id,username, name, age, balance) values(1,'liubei', '劉備', 20, 100.00);
insert into user(id,username, name, age, balance) values(2,'guanyu', '關羽', 20, 100.00);
insert into user(id,username, name, age, balance) values(3,'zhangfei', '張飛', 20, 100.00);
insert into user(id,username, name, age, balance) values(4,'machao', '馬超', 20, 100.00);
data.sql
drop table user if exists;
create table user(
    id bigint generated by default as identity,
    username varchar(40),
    name varchar(20),
    age int(3),
    balance decimal(10,2), 
    primary key(id)
);
schema.sql

(3)、配置文件application.yml

 1 server:
 2   # 服務器端口號
 3   port: 6900
 4 spring:
 5   jpa:
 6     # 是否生成ddl語句
 7     generate-ddl: false
 8     # 是否打印sql語句
 9     show-sql: true
10     hibernate:
11       # 自動生成ddl,由於指定了具體的ddl,此處設置為none
12       ddl-auto: none
13   datasource:
14     # 使用H2數據庫
15     platform: h2
16     # 指定生成數據庫的schema文件位置
17     schema: classpath:schema.sql
18     # 指定插入數據庫語句的腳本位置
19     data: classpath:data.sql
20     
21 # 配置日志打印信息    
22 logging:
23   level:
24     root: INFO
25     org.hibernate: INFO
26     org.hibernate.type.descriptor.sql.BasicBinder: TRACE
27     org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
28     com.itmuch: DEBUG
schema.sql

(4)、創建UserController

 1 package com.mmzs.cloud.controller;
 2 
 3 import javax.annotation.Resource;
 4 import javax.websocket.server.PathParam;
 5 
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.web.bind.annotation.GetMapping;
 8 import org.springframework.web.bind.annotation.PathVariable;
 9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.bind.annotation.RestController;
11 
12 import com.mmzs.cloud.UserRepository;
13 import com.mmzs.cloud.entity.User;
14 
15 /**
16  * @author: mmzsit
17  * @date:   2018年8月17日
18  * @Description: 
19  * 博客地址:https://www.cnblogs.com/mmzs/p/9282412.html
20  * @version V1.0
21 */
22 @RestController
23 public class UserController {
24     
25     @Resource
26     private UserRepository userRepository;
27     
28     //第一種方式
29     @GetMapping("/user/{id}")
30     //第二種方式
31     //@RequestMapping(value="/xxx",method=org.springframework.web.bind.annotation.RequestMethod.GET)
32     //第一種和第二種方式其實是等效的
33     public User findById(@PathVariable Long id){
34         return this.userRepository.getOne(id);
35     }
36 }
UserController

(5)、創建UserRepository

 1 package com.mmzs.cloud;
 2 
 3 
 4 import org.springframework.data.jpa.repository.JpaRepository;
 5 import org.springframework.stereotype.Repository;
 6 
 7 import com.mmzs.cloud.entity.User;
 8 
 9 /**
10  * @author: mmzsit
11  * @date:   2018年8月17日
12  * @Description: 
13  * 博客地址:https://www.cnblogs.com/mmzs/p/9282412.html
14  * @version V1.0
15 */
16 @Repository
17 public interface UserRepository extends JpaRepository<User, Long>{
18 
19     /**
20      * @Description: 
21      * @param:  @param id
22      * @param:  @return
23      * @return: User
24      * @throws
25     */
26 //    User findOne(Long id);
27 
28     
29 
30 }
UserRepository

(6)、創建實體類User

 1 package com.mmzs.cloud.entity;
 2 
 3 import java.math.BigDecimal;
 4 
 5 import javax.persistence.Column;
 6 import javax.persistence.Entity;
 7 import javax.persistence.GeneratedValue;
 8 import javax.persistence.GenerationType;
 9 import javax.persistence.Id;
10 
11 import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
12 
13 /**
14  * @author: mmzsit
15  * @date:   2018年8月17日
16  * @Description: 
17  * 博客地址:https://www.cnblogs.com/mmzs/p/9282412.html
18  * @version V1.0
19 */
20 @Entity
21 @JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
22 public class User {
23     
24     @SuppressWarnings("unused")
25     private static final long serialVersionUID = 1L;
26     
27     @Id
28     @GeneratedValue(strategy=GenerationType.AUTO)
29     private Long id;
30     @Column
31     private String username;
32     @Column
33     private String name;
34     @Column
35     private Short age;
36     @Column
37     private BigDecimal balance;
38     
39     public Long getId() {
40         return id;
41     }
42     public String getUsername() {
43         return username;
44     }
45     public String getName() {
46         return name;
47     }
48     public Short getAge() {
49         return age;
50     }
51     public BigDecimal getBalance() {
52         return balance;
53     }
54     public void setId(Long id) {
55         this.id = id;
56     }
57     public void setUsername(String username) {
58         this.username = username;
59     }
60     public void setName(String name) {
61         this.name = name;
62     }
63     public void setAge(Short age) {
64         this.age = age;
65     }
66     public void setBalance(BigDecimal balance) {
67         this.balance = balance;
68     }
69     
70 }
User

注:此處采用的是jpa,使用的是h2數據庫,如果訪問時出現實體類轉化json格式錯誤,則需要在實體類前面加上如下這句注釋:

@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })

錯誤提示:disable SerializationFeature.FAIL_ON_EMPTY_BEANS

(7)、執行MicroserviceSimpleProviderUserApplication類,然后進行訪問測試

 

3、編寫一個服務消費者

登陸:http://start.spring.io/

填寫信息:

(1)、將生成的maven工程導入eclipse

然后一次創建如下選中的類和配置文件。

(2)、配置文件application.yml

server:
  port: 6901

(3)、創建GoodsController

 1 package com.mmzs.cloud.controller;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.beans.factory.annotation.Value;
 5 import org.springframework.web.bind.annotation.GetMapping;
 6 import org.springframework.web.bind.annotation.PathVariable;
 7 import org.springframework.web.bind.annotation.RestController;
 8 import org.springframework.web.client.RestTemplate;
 9 
10 import com.mmzs.cloud.entity.User;
11 
12 /**
13  * @author: mmzsit
14  * @date: 2018年8月17日
15  * @Description: 博客地址:https://www.cnblogs.com/mmzs/p/9282412.html
16  * @version V1.0
17  */
18 @RestController
19 public class GoodsController {
20     @Autowired
21     private RestTemplate restTemplate;
22 
23     @GetMapping("/goods/{id}")
24     public User findById(@PathVariable Long id) {
25         //采用了硬編碼注冊user服務
26         return this.restTemplate.getForObject("http://localhost:6900/user/" + id, User.class);
27     }
28 }
GoodsController

(4)、創建實體類User

 1 package com.mmzs.cloud.entity;
 2 
 3 import java.io.Serializable;
 4 import java.math.BigDecimal;
 5 
 6 /**
 7  * @author: mmzsit
 8  * @date:   2018年8月17日
 9  * @Description: 
10  * 博客地址:https://www.cnblogs.com/mmzs/p/9282412.html
11  * @version V1.0
12 */
13 
14 public class User implements Serializable{
15     
16     private static final long serialVersionUID = -7125209803403015533L;
17     
18     private Long id;
19     private String username;
20     private String name;
21     private Short age;
22     private BigDecimal balance;
23     public Long getId() {
24         return id;
25     }
26     public void setId(Long id) {
27         this.id = id;
28     }
29     public String getUsername() {
30         return username;
31     }
32     public void setUsername(String username) {
33         this.username = username;
34     }
35     public String getName() {
36         return name;
37     }
38     public void setName(String name) {
39         this.name = name;
40     }
41     public Short getAge() {
42         return age;
43     }
44     public void setAge(Short age) {
45         this.age = age;
46     }
47     public BigDecimal getBalance() {
48         return balance;
49     }
50     public void setBalance(BigDecimal balance) {
51         this.balance = balance;
52     }
53     
54 }
User

(5)、在MicroserviceSimpleConsumerGoodsApplication類中注入Bean

 其中11-16行表示注入的Bean

 1 package com.mmzs.cloud;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.context.annotation.Bean;
 6 import org.springframework.web.client.RestTemplate;
 7 
 8 @SpringBootApplication
 9 public class MicroserviceSimpleConsumerGoodsApplication {
10     
11     @Bean
12     public RestTemplate restTemplate() {
13         return new RestTemplate();
14     }
15     //12、13、14、行相當於16行
16     //private RestTemplate restTemplate = new RestTemplate();
17 
18     public static void main(String[] args) {
19         SpringApplication.run(MicroserviceSimpleConsumerGoodsApplication.class, args);
20     }
21 }
MicroserviceSimpleConsumerGoodsApplication

(5)、執行MicroserviceSimpleConsumerGoodsApplication類,然后進行訪問測試

4、小小優化一下

主要優化的點是在GoodsController類中的硬編碼部分。簡單優化如下:

@RestController
public class GoodsController {
    @Autowired
    private RestTemplate restTemplate;

    //優化部分
    @Value("${user.userServicePath}")
    private String userServicePath; 
    
    //優化后此處的硬編碼字符串,修改為變量獲取
    @GetMapping("/goods/{id}")
    public User findById(@PathVariable Long id) {
        //采用了硬編碼注冊user服務
        return this.restTemplate.getForObject(this.userServicePath + id, User.class);
    }
}

這樣子的話,userServicePath的具體值需要通過配置文件application.yml來配置,故application.yml文件修改為:

server:
  port: 6901
# 優化部分
user:
  userServicePath: http://localhost:6900/user/

注: 其實這樣子的優化也不是很好,因為當微服務過多時,層層調用,需要修改的部分也會越來越多,不便於維護和修改。具體措施,詳見下回分解。

五、代碼下載

點擊這里跳轉

如果需要積分的話,其實大家沒必要消耗積分進行下載,按照文章內容一步一步來,絕對是可以完美測試成功的,動手過程,讓影響更加深刻,不是嗎? 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM