springcloud(二)-最簡單的實戰


技術儲備

Spring cloud並不是面向零基礎開發人員,它有一定的學習曲線。

  • 語言基礎:spring cloud是一個基於Java語言的工具套件,所以學習它需要一定的Java基礎。當然,spring cloud同樣也支持使用Scala,Groovy等語言進行開發。
  • Spring boot:Spring cloud是基於spring boot構建的,因此它延續了spring boot的契約模式以及開發模式。學習spring cloud之前需要學習spring boot,至少先入門。
  • 項目管理與構建工具:目前業界比較主流的項目管理與構建工具有maven和Gradle等,我想大家最常用的,或者說用的最多的還是maven吧。

工具及軟件版本

  • JDK:springboot官方推薦使用的是JDK1.8,當然Spring cloud推薦的也是JDK1.8。所以你懂的呀,不用糾結低版本的了呀。
  • Spring boot:使用Spring Boot 1.5.9.RELEASE。雖然現在Spring boot2.0出來了,但是需要結合Spring cloud的版本兼容。
  • Spring cloud:使用 Spring Cloud Edgware RELEASE.(你要想用最新的也沒問題,但是要注意springboot兼容性)
  • maven:我用的是3.5.0啊。無所謂
  • 開發工具:我獨愛eclipse。雖然我知道IntelliJ IDEA 可能更優秀。

服務的提供者與服務的消費者

使用微服務構建的是分布式系統,微服務之間通過網絡進行通信。我們使用服務提供者與服務消費者來描述為服務之間的調用關系。

名詞 定義
服務提供者 服務的被調用方(即:為其他服務提供服務的服務)
服務消費者 服務的調用方(即:依賴其他服務的服務)

 

 

舉個生活中的例子:我們去超市買東西,商品又是由廠商提供給超市的。在這一過程中,廠商就是服務的提高者,超市是服務的消費者。

我們只需要到超市消費就行,不用到廠商去了。

編寫服務提供者

先准備下數據庫和數據

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(40) DEFAULT NULL,
  `name` varchar(20) DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `balance` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'account1', '張三', '20', '98.23');
INSERT INTO `user` VALUES ('2', 'account2', '李四', '24', '23.12');
INSERT INTO `user` VALUES ('3', 'account3', '王五', '32', '42.12');

創建一個springboot項目,ArtifactId為microservice-simple-provider-user

pom.xml

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 3   <modelVersion>4.0.0</modelVersion>
 4 
 5   <groupId>com.itmuch.cloud</groupId>
 6   <artifactId>microservice-simple-provider-user</artifactId>
 7   <version>0.0.1-SNAPSHOT</version>
 8   <packaging>jar</packaging>
 9 
10   <name>microservice-simple-provider-user</name>
11   <url>http://maven.apache.org</url>
12   
13   <parent>
14         <groupId>org.springframework.boot</groupId>
15         <artifactId>spring-boot-starter-parent</artifactId>
16         <version>1.5.9.RELEASE</version>
17     </parent>
18 
19   <properties>
20     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
21     <java.version>1.8</java.version>
22   </properties>
23 
24   <dependencies>
25            <dependency>
26             <groupId>org.springframework.boot</groupId>
27             <artifactId>spring-boot-starter-web</artifactId>
28         </dependency>
29         <dependency>
30                <groupId>mysql</groupId>
31                <artifactId>mysql-connector-java</artifactId>
32         </dependency>
33         <dependency>
34             <groupId>org.springframework.boot</groupId>
35             <artifactId>spring-boot-devtools</artifactId>
36             <optional>true</optional> <!-- 這個需要為 true 熱部署才有效 -->
37         </dependency>
38         <!-- jpa-->
39         <dependency>
40             <groupId>org.springframework.boot</groupId>
41             <artifactId>spring-boot-starter-data-jpa</artifactId>
42         </dependency>
43   </dependencies>
44   
45 <!--   引入spring cloud 的依賴 -->
46     <dependencyManagement>
47         <dependencies>
48             <dependency>
49                 <groupId>org.springframework.cloud</groupId>
50                 <artifactId>spring-cloud-dependencies</artifactId>
51                 <version>Edgware.RELEASE</version>
52                 <type>pom</type>
53                 <scope>import</scope>
54             </dependency>
55         </dependencies>
56     </dependencyManagement>
57   
58 <!--   添加spring-boot 的maven插件 -->
59     <build>
60         <plugins>
61             <plugin>
62                 <groupId>org.springframework.boot</groupId>
63                 <artifactId>spring-boot-maven-plugin</artifactId>
64             </plugin>
65         </plugins>
66     </build>
67   
68 </project>
點擊展開

用戶實體類User.java

 1 package com.itmuch.cloud.entity;
 2 
 3 import java.math.BigDecimal;
 4 
 5 import javax.persistence.Entity;
 6 import javax.persistence.GeneratedValue;
 7 import javax.persistence.GenerationType;
 8 import javax.persistence.Id;
 9 
10 @Entity
11 public class User {
12     @Id
13     @GeneratedValue(strategy = GenerationType.AUTO)
14     private Long id;
15     private String username;
16     private String name;
17     private Integer age;
18     private BigDecimal balance;
19 
20     public Long getId() {
21         return id;
22     }
23 
24     public void setId(Long id) {
25         this.id = id;
26     }
27 
28     public String getUsername() {
29         return username;
30     }
31 
32     public void setUsername(String username) {
33         this.username = username;
34     }
35 
36     public String getName() {
37         return name;
38     }
39 
40     public void setName(String name) {
41         this.name = name;
42     }
43 
44     public Integer getAge() {
45         return age;
46     }
47 
48     public void setAge(Integer age) {
49         this.age = age;
50     }
51 
52     public BigDecimal getBalance() {
53         return balance;
54     }
55 
56     public void setBalance(BigDecimal balance) {
57         this.balance = balance;
58     }
59 
60 }
點擊展開

DAO

package com.itmuch.cloud.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.itmuch.cloud.entity.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

}

創建Controller

package com.itmuch.cloud.controller;

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 com.itmuch.cloud.dao.UserRepository;
import com.itmuch.cloud.entity.User;

@RestController
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/{id}")
    public User findById(@PathVariable Long id) {
        User findOne = userRepository.findOne(id);
        return findOne;
    }
}

最后還有一個啟動類不用說了吧。

配置文件application.yml

server:
  port: 8084
spring:
  application:
    name: microservice-provider-user
  jpa:
    generate-ddl: false
    show-sql: true
    database-platform: org.hibernate.dialect.MySQL5Dialect
    hibernate:
      ddl-auto: none
  datasource:
    url: jdbc:mysql://localhost:3306/cloud?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: 1234
    driver-class-name: com.mysql.jdbc.Driver
  http:
    multipart:
      maxFileSize: 100Mb
      maxRequestSize: 100Mb
logging:
  level:
    root: INFO
    org.hibernate: INFO
    org.hibernate.type.descriptor.sql.BasicBinder: TRACE
    org.hibernate.type.descriptor.sql.BasicExtractor: TRACE

測試

啟動訪問localhost:8084/1. 試下結果。

{"id":1,"username":"account1","name":"張三","age":20,"balance":98.23}

哦了。

 

編寫服務消費者

創建一個maven項目,ArtifactId是microservice-simple-consumer-movie.

pom.xml

一樣一樣的。

POJO類User.java

 1 package com.itmuch.cloud.pojo;
 2 
 3 import java.math.BigDecimal;
 4 
 5 public class User {
 6     private Long id;
 7     private String username;
 8     private String name;
 9     private Integer age;
10     private BigDecimal balance;
11 
12     public Long getId() {
13         return id;
14     }
15 
16     public void setId(Long id) {
17         this.id = id;
18     }
19 
20     public String getUsername() {
21         return username;
22     }
23 
24     public void setUsername(String username) {
25         this.username = username;
26     }
27 
28     public String getName() {
29         return name;
30     }
31 
32     public void setName(String name) {
33         this.name = name;
34     }
35 
36     public Integer getAge() {
37         return age;
38     }
39 
40     public void setAge(Integer age) {
41         this.age = age;
42     }
43 
44     public BigDecimal getBalance() {
45         return balance;
46     }
47 
48     public void setBalance(BigDecimal balance) {
49         this.balance = balance;
50     }
51 
52 }
點擊展開

Controller類

 1 package com.itmuch.cloud.controller;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.web.bind.annotation.GetMapping;
 5 import org.springframework.web.bind.annotation.PathVariable;
 6 import org.springframework.web.bind.annotation.RestController;
 7 import org.springframework.web.client.RestTemplate;
 8 
 9 import com.itmuch.cloud.pojo.User;
10 
11 @RestController
12 public class MovieController {
13     @Autowired
14     private RestTemplate restTemplate;
15 
16     @GetMapping("/user/{id}")
17     public User findById(@PathVariable Long id) {
18         return restTemplate.getForObject("http://localhost:8084/" + id, User.class);
19     }
20 }
點擊展開

啟動類

 1 package com.itmuch.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 ConsumerMovieApplication {
10     @Bean
11     public RestTemplate restTemplate() {
12         return new RestTemplate();
13     }
14 
15     public static void main(String[] args) {
16         SpringApplication.run(ConsumerMovieApplication.class, args);
17     }
18 }
點擊展開

配置文件application.yml

server:
  port: 8082

測試

好了,你把兩個服務都啟動,訪問http://127.0.0.1:8082/user/1, 看結果。

{"id":1,"username":"account1","name":"張三","age":20,"balance":98.23}

 

OK了。

 


免責聲明!

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



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