javascript
Spring Cloud【Finchley】-01服务提供者与服务消费者
文章目錄
- Spring Cloud總覽
- 概述
- 示例
- 場景描述
- 用戶微服務
- 新建Spring Boot服務
- 項目結構
- 用戶庫表
- Model
- Dao層
- Service
- Controller 暴露Rest API
- 配置文件application.yml
- 測試
- 電影微服務
- 新建Spring Boot服務
- 項目結構
- Controller通過 RestTemplate 調用用戶微服務提供的服務
- 啟動類入口處,通過@Bean實例化RestTemplate
- 配置文件 application.yml
- 測試
- 示例的缺點
Spring Cloud總覽
概述
服務提供者: 服務的被調用發,為其他服務提供服務的服務
服務消費者: 服務的調用方,即依賴其他服務的服務
示例
場景描述
圍繞該場景,需要兩個微服務
- 用戶微服務,作為服務提供者為電影微服務提供服務
- 電影微服務,作為消費者調用用戶微服務提供的服務
用戶微服務
Spring Boot 2.1.1
Spring Data JPA
H2
lombok簡化編碼
新建Spring Boot服務
項目結構
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"><modelVersion>4.0.0</modelVersion><groupId>com.artisan</groupId><artifactId>micorservice-simple-provider-user</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>micorservice-simple-provider-user</name><description>Demo project for Spring Cloud</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.1.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.4</version><scope>provided</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>用戶庫表
簡單起見,我們使用H2數據庫
schema.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) );data.sql
insert into user(id,username, name, age, balance) values(1,'user1', '張三', 20, 100.00); insert into user(id,username, name, age, balance) values(2,'user2', '李四', 20, 100.00); insert into user(id,username, name, age, balance) values(3,'user3', '王五', 20, 100.00); insert into user(id,username, name, age, balance) values(4,'user4', '馬六', 20, 100.00);Model
為了簡化代碼,使用了lombok的@Data注解
package com.artisan.microservice.model;import java.io.Serializable; import java.math.BigDecimal;import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id;import lombok.Data;@Entity @Data public class User implements Serializable {private static final long serialVersionUID = 226695758444267342L;@Id@GeneratedValue(strategy=GenerationType.AUTO)private Long id ;@Columnprivate String username;@Columnprivate String name;@Columnprivate Integer age;@Columnprivate BigDecimal balance;}Dao層
使用Spring Data JPA操作數據庫
package com.artisan.microservice.repository;import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;import com.artisan.microservice.model.User;@Repository public interface UserRepository extends JpaRepository<User,Long>{}Service
按道理都應該有Service層,這里demo比較簡單,省略也可以,直接在Controller層調用Dao層
Controller 暴露Rest API
package com.artisan.microservice.controller;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController;import com.artisan.microservice.model.User; import com.artisan.microservice.repository.UserRepository;@RestController public class UserController {@Autowiredprivate UserRepository userRepository;@GetMapping("/user/{id}")public User findById(@PathVariable Long id) {User user = new User();user.setId(id);User user2 = new User();user2.setName("no this user");// 我們使用的spring boot2.1.1版本中關聯使用的spring data jpa不再支持findone(id)方法,改成如下寫法return userRepository.findOne(Example.of(user)).orElse(user2); } }配置文件application.yml
server:port: 7900 spring:jpa:generate-ddl: falseshow-sql: truehibernate:ddl-auto: nonedatasource:platform: h2schema: classpath:schema.sqldata: classpath:data.sql logging:level:root: INFOorg.hibernate: INFOorg.hibernate.type.descriptor.sql.BasicBinder: TRACEorg.hibernate.type.descriptor.sql.BasicExtractor: TRACEcom.artisan: DEBUG測試
package com.artisan.microservice;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class MicorserviceSimpleProviderUserApplication {public static void main(String[] args) {SpringApplication.run(MicorserviceSimpleProviderUserApplication.class, args);} }右鍵–Run As --Spring Boot App,啟動成功后
訪問數據庫中存在的用戶
http://localhost:7900/user/1
http://localhost:7900/user/2
{"id":2,"username":"user2","name":"李四","age":20,"balance":100.00}http://localhost:7900/user/3
{"id":3,"username":"user3","name":"王五","age":20,"balance":100.00}http://localhost:7900/user/4
{"id":4,"username":"user4","name":"馬六","age":20,"balance":100.00}訪問數據庫中不存在的一個用戶
http://localhost:7900/user/66
電影微服務
新建Spring Boot服務
如用戶微服務,只不過我們這里僅僅作為消費者,僅使用web即可。
項目結構
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"><modelVersion>4.0.0</modelVersion><groupId>com.artisan</groupId><artifactId>micorservice-simple-consumer-movie</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>micorservice-simple-consumer-movie</name><description>Demo project for Spring Cloud</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.1.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.4</version><scope>provided</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>Controller通過 RestTemplate 調用用戶微服務提供的服務
因為僅僅作為服務消費者,所有只要在Controller層調用對應的rest接口即可
package com.artisan.microservice.controller;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; 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;import com.artisan.microservice.model.User;@RestController public class MovieController {@Autowiredprivate RestTemplate restTemplate;@Value("${user.userServicePath}")private String userServicePath;@GetMapping("/movie/{id}")public User findById(@PathVariable Long id) {return this.restTemplate.getForObject(this.userServicePath + id, User.class);} }用到了User類,新建個User.java
package com.artisan.microservice.model;import java.io.Serializable; import java.math.BigDecimal;import lombok.Data;@Data public class User implements Serializable {private static final long serialVersionUID = 8912111288470833198L;private Long id;private String username;private String name;private Integer age;private BigDecimal balance;}啟動類入口處,通過@Bean實例化RestTemplate
通過@Bean實例化RestTemplate
package com.artisan.microservice;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate;@SpringBootApplication public class MicorserviceSimpleConsumerMovieApplication {@Beanpublic RestTemplate restTemplate(){return new RestTemplate();}public static void main(String[] args) {SpringApplication.run(MicorserviceSimpleConsumerMovieApplication.class, args);} }配置文件 application.yml
配置端口及用戶微服務的地址
server:port: 7901 user: userServicePath: http://localhost:7900/user/測試
啟動用戶微服務,訪問7901
訪問數據庫中存在的用戶
http://localhost:7901/movie/1
http://localhost:7901/movie/2
{"id":2,"username":"user2","name":"李四","age":20,"balance":100.00}http://localhost:7901/movie/3
{"id":3,"username":"user3","name":"王五","age":20,"balance":100.00}http://localhost:7901/movie/4
{"id":4,"username":"user4","name":"馬六","age":20,"balance":100.00}訪問數據庫中不存在的一個用戶
http://localhost:7901/movie/66
成功調用到了用戶微服務對外提供的服務。
示例的缺點
不難發現,雖然我們把用戶微服務對外提供的接口地址配置在了配置文件中,然后通過@Value的方式去加載該屬性,但是一旦用戶微服務修改了地址,電影微服務作為消費者也要修改對應的地址,多了的話,也是很難管理
第二個原因,如果存在多個用戶微服務,如何進行負載? nginx固然可以,如果這種服務比較多,依賴nginx, 增加節點還是需要修改nginx配置文件,比較頭疼
所以 接下來我們來看下服務發現與服務注冊,這里主要說的是Spring Cloud支持比較好的Eureka
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Spring Cloud【Finchley】-01服务提供者与服务消费者的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Boot2.x-06Spr
- 下一篇: Spring Cloud【Finchle