天天看點

Spring Cloud(Greenwich版)-01-服務生産者與服務消費者

Spring Cloud(Greenwich版)-01-服務生産者與服務消費者

概念

服務生産者:服務的被調用方(即:為其他服務提供服務的服務)
服務消費者:服務的調用方(即:依賴其他服務的服務)
           

以微商城系統為例:使用者發起購買商品請求,調用商品資訊微服務是否滿足購買條件,如果滿足那就去查使用者資訊,如下圖所示:

Spring Cloud(Greenwich版)-01-服務生産者與服務消費者

商品微服務是服務消費者,使用者微服務就是服務生産者。

接下來以“微商城”系統為例,編寫服務生産者和消費者。

編寫一個服務生産者

第一步:通過start.spring.io建構服務生産者項目

打開位址:https://start.spring.io

如下圖所示,選擇相應資訊:

Spring Cloud(Greenwich版)-01-服務生産者與服務消費者

增加Dependencies子產品支援:

1、web

2、jpa 通路持久層

3、h2 内嵌資料庫(可以做一些資料的展示)

可以直接搜尋添加即可,添加完成後點選Generate the project,将會生産代碼的壓縮包,解壓導入idea開發工具即可。

第二步:編寫sql腳本

由于用的是内嵌h2資料庫,是以這裡編寫建立使用者表的sql腳本和資料:

schema.sql

drop table user if exists;
create table user(
  id bigint generated by default as identity,
  user_name varchar(40),
  name varchar(20),
  age int(3),
  balance decimal(10,2),
  primary key(id)
)
           

data.sql

insert into user(id,user_name,name,age,balance) values (1,'tangseng','唐僧',20,98.00);
insert into user(id,user_name,name,age,balance) values (2,'wukong','齊天大聖',18,10000.00);
insert into user(id,user_name,name,age,balance) values (3,'bajie','二師兄',25,898.00);
insert into user(id,user_name,name,age,balance) values (4,'wujing','三師弟',35,998.00);
           
第三步:application.ml配置檔案
server:
  port: 8080
spring:
  spa:
    generate-ddl: false
    show-sql: true
    hibernate:
      ddl-auto: none
  datasource:
    platform: h2
    schema: classpath:schema.sql
    data: classpath:data.sql
logging:
  level:
    root: INFO
    org.hibernate: INFO
    org.hibernate.type.descriptor.sql.BasicBinder: TRACE
    org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
    com.itunion: DEBUG
           
第三步:編寫User實體類
@Entity
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column
    private String userName;
    @Column
    private String name;
    @Column
    private int age;
    @Column
    private BigDecimal balance;
   ......省略get/set方法
}
           
第四步:編寫UserRepository
@Repository
public interface UserRepository extends JpaRepository<User,Long> {
}
           

這裡繼承了JpaRepository。

第五步:編寫UserController
@RestController
public class UserController {
    @Autowired
    private UserRepository userRepository;
    @GetMapping("/simple/{id}")
    public User findById(@PathVariable Long id){
        User user = this.userRepository.getOne(id);
        System.out.println(user.toString());
        return user;
    }
}
           
第六步:測試

浏覽器輸入位址:http://127.0.0.1:8080/simple/2

{"id":2,"userName":"wukong","name":"齊天大聖","age":18,"balance":10000.00}
           

好了,到這裡一個簡單的微服務服務生産者已經編寫完成。

備注:代碼結構如下

Spring Cloud(Greenwich版)-01-服務生産者與服務消費者

編寫一個服務消費者

第一步:通過start.spring.io建構服務消費者項目

和上面步驟一樣,Artifact需要修改,如下圖所示:

Spring Cloud(Greenwich版)-01-服務生産者與服務消費者

增加Dependencies子產品支援:

1、web

隻需要web就可以了,添加完成後點選Generate the project,将會生産代碼的壓縮包,解壓導入idea開發工具。

第二步:編寫User實體類
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
public class User {
    private Long id;
    private String userName;
    private String name;
    private int age;
    private BigDecimal balance;
    ......省略其他get/set方法
}
           

這裡隻是做一個接收資料的映射,不需要jpa的注解。

第三步:編寫GoodsController
@RestController
public class GoodsController {
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/goods/{id}")
    public User findById(@PathVariable Long id){
        return this.restTemplate.getForObject("http://127.0.0.1:8080/simple/"+id,User.class);
    }
}
           

根據傳入的id通過restTemplate的方式去查詢服務生産者擷取使用者資訊。

第四步:配置application.yml檔案
server:
  port: 8081
           
第五步:啟動測試

服務生産者和消費者都需要啟動。

通路服務消費者位址:http://127.0.0.1:8081/goods/2

報錯資訊:

Description:
Field restTemplate in com.itunion.cloud.web.controller.GoodsController required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
           

錯誤原因:RestTemplate 未執行個體化,MicroserviceSimpleConsumerGoodsApplication增加RestTemplate執行個體化代碼

@Bean
	public RestTemplate restTemplate(){
		return new RestTemplate();
	};
           

再次啟動并通路:http://127.0.0.1:8081/goods/2

傳回結果

{"id":2,"userName":"wukong","name":"齊天大聖","age":18,"balance":10000.00}
           

總結

簡單的服務生産者和服務消費者已經實作了,使用者在購買商品的時候調用服務消費者的goods接口,然後服務消費者通過RestTemplate調用服務生産者simple查詢使用者資訊。

文中為了快速實作生産者和消費者的關系,采取了一些寫死的方式,在實際分布式架構中是不行的,不過沒關系後面我們慢慢來使項目更加健壯。

問題

1、生産者和消費者應用如何進行監控?并且也沒有畫闆,啥名額都沒得。沒辦法監控系統壓力、QPS、記憶體、CPU和日活的可視化面闆,是不是很low?

2、上面提到的寫死問題,微服務位址和端口都是固定的,在實際項目場景中每次位址發生變更都需要去修改代碼(如果用Docker容器化部署那就更酸爽了)。

3、負載均衡怎麼辦?

4、服務直接的容錯機制如何處理?

5、使用者的認證和授權呢?

6、應用發生故障,如何能夠進行問題追蹤快速定位?

繼續閱讀