SpingCloud微服务架构学习(一)之服务提供者与服务消费者

  微服务构建的是分布式系统,各个微服务之间通过网络进行服务调用,这就有了服务提供者(被调用方)和服务消费者(调用方),以电影售票系统为例,假设服务调用关系如下图所示:

SpingCloud微服务架构学习(一)之服务提供者与服务消费者

围绕此场景,我们先编写一个用户微服务,再编写一个电影微服务。

一、编写服务提供者

1、打开start.spring.io,添加web,jpa,h2依赖,设置group为com.cloud,Artifact为microservice-provider-user,这个详细的教程可以参考我之前关于springboot的几篇博客,然后生成一个boot项目,pom文件内容如下:

<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.cloud</groupId>
<artifactId>microservice-provider-user</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>microservice-provider-user</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</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>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>
<version>3.0</version>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>

如果加载到eclipse后没有生产maven依赖包,可以右击项目->Maven4MyEclipse->updateProject试试。

2、在resource下创建schemal.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)
);

3、在resource下创建data.sql内容如下:

INSERT INTO user (id, username, name, age, balance) VALUES (1, 'account1', '刘备', 40, 5000.00);
INSERT INTO user (id, username, name, age, balance) VALUES (2, 'account2', '关羽', 35, 4000.00);
INSERT INTO user (id, username, name, age, balance) VALUES (3, 'account3', '张飞', 30, 3000.00);

4、创建用户实体:

package com.cloud.microserviceprovideruser.entity;

import java.math.BigDecimal;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column
private String username;
@Column
private String name;
@Column
private Integer age;
@Column
private BigDecimal balance;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}

}

5、创建Dao:

package com.cloud.microserviceprovideruser.dao;

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

import org.springframework.stereotype.Repository;

import com.cloud.microserviceprovideruser.entity.User;
@Repository
public interface UserRepository extends JpaRepository<User,Long>{
}

6、创建Controller:

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

@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/{id}")
public User findById(@PathVariable Long id){
return userRepository.findById(id).get();
}
}

7、编写配置文件(注意文件内容填写格式要求非常严格,空格一定要是空格):

server:
  port: 8080
spring:
  jpa:
    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.BasticBinder: TRACE
    org.hibernate.type.descriptor.sql.BasticExtractor: TRACE

访问http://localhost:8080/1获得结果:

{"id":1,"username":"account1","name":"刘备","age":40,"balance":5000.00}
至此服务提供者创建完毕!

二、创建服务消费者:

1、将创建的生产者代码复制一份,然后修改一下,项目名改为microservice-consumer-movie,需要改pom和.project文件里相关名字的部分。

<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.cloud</groupId>
<artifactId>microservice-consumer-movie</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>microservice-consumer-movie</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</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>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>
<version>3.0</version>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>

2、将user实体类的注解删掉,dao删掉,启动类改一下

package com.cloud.microserviceconsumermovie.entity;

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 com.fasterxml.jackson.annotation.JsonIgnoreProperties;
public class User {
private Long id;
private String username;
private String name;
private Integer age;
private BigDecimal balance;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}

}

package com.cloud.microserviceconsumermovie;

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 MicroserviceConsumerMovieApplication {
/**
* Bean是注解实例化该Bean并使用该方法的名称命名,
相当于将restTemplate注入到spring容器中。
*/
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(MicroserviceConsumerMovieApplication.class, args);
}
}

3、创建Controller,使用RestTemplate请求用户微服务的api。

package com.cloud.microserviceconsumermovie.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 org.springframework.web.client.RestTemplate;

import com.cloud.microserviceconsumermovie.entity.User;

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

@GetMapping("/user/{id}")
public User findById(@PathVariable Long id){
return this.restTemplate.getForObject("http://localhost:8080/"+id, User.class);
}
}

4、设置application.yml内容:

server:
  port: 8090

启动两个项目,访问http://localhost:8090/user/1,得到返回结果:

{"id":1,"username":"account1","name":"刘备","age":40,"balance":5000.00}
这就说明消费者已经正常访问服务提供者了!
上一篇:c语言实现BMP图像转换为灰度图


下一篇:统计学习方法