spring cloud微服务架构 服务提供者和服务消费者

Posted Antony

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring cloud微服务架构 服务提供者和服务消费者相关的知识,希望对你有一定的参考价值。

服务提供者和服务消费者

 

下面这张表格,简单描述了服务提供者/消费者是什么:
 
| 名词 | 概念 |
| ----- | ----------------------- |
| 服务提供者 | 服务的被调用方(即:为其他服务提供服务的服务) |
| 服务消费者 | 服务的调用方(即:依赖其他服务的服务) |
 
服务提供者代码示例
这是一个稍微有点复杂的程序。我们使用spring-data-jpa操作h2数据库,同时将该服务注册到注册中心Eureka中。
1、创建一个Maven工程,并在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>

    <artifactId>microservice-provider-user</artifactId>
    <packaging>jar</packaging>

    <name>microservice-provider-user</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.xujin.study</groupId>
        <artifactId>microservice-spring-cloud</artifactId>
        <version>0.0.1-SNAPSHOT</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.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
    </dependencies>

</project>

2、编写建表语句init.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、编写插入语句 insert.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);

4、编写启动类MicroserviceSimpleProviderUserApplication

package com.xujin.study;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class MicroserviceSimpleProviderUserApplication {

    public static void main(String[] args) {
        SpringApplication.run(MicroserviceSimpleProviderUserApplication.class, args);
    }
}

5、编写实体类User

package com.xujin.study.entity;

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;

@Entity
public class User implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO )
    private Long id;
    
    @Column
    private String username;
    
    @Column
    private String name;
    
    @Column
    private Short 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 Short getAge() {
        return age;
    }

    public void setAge(Short age) {
        this.age = age;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }
    
}

6、编写Repository接口UserRepository

package com.xujin.study.repository;

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

import com.xujin.study.entity.User;

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

}

7、编写service业务类UserService

package com.xujin.study.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xujin.study.entity.User;
import com.xujin.study.repository.UserRepository;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    public User findOne(Long id){
        return userRepository.findOne(id);
    }
    
    
}

8、编写控制器UserController

package com.xujin.study.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.xujin.study.entity.User;
import com.xujin.study.service.UserService;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    
    @GetMapping("/simple/{id}")
    public User findById(@PathVariable Long id){
        return this.userService.findOne(id);
    }

}

9、配置文件application.yml

server:
  port: 7901
  #  contextPath: /microservice-simple-provider-user   指定项目部署使用项目名
spring:
  application:
    name: microservice-provider-user    # 项目名称尽量用小写(注册到eureka的名字)
  jpa:
    generate-ddl: false
    show-sql: true
    hibernate:
      ddl-auto: none
  datasource:                           # 指定数据源
    platform: h2                        # 指定数据源类型
    schema: classpath:init.sql          # 指定h2数据库的建表脚本
    data: classpath:insert.sql          # 指定h2数据库的insert脚本
logging:
  level:
    root: INFO
    org.hibernate: INFO
    org.hibernate.type.descriptor.sql.BasicBinder: TRACE
    org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
    com.itmuch.youran.persistence: ERROR
eureka:
  client:
    serviceUrl:
      defaultZone: http://root:[email protected]:8761/eureka/
  instance:
    prefer-ip-address: true     #指定应用微服务在eureka上面的链接为IP地址
    instance-id: ${spring.application.name}:${server.port}

10、访问   http://localhost:7901/simple/1

{"id":1,"username":"user1","name":"张三","age":20,"balance":100.00}

以上是关于spring cloud微服务架构 服务提供者和服务消费者的主要内容,如果未能解决你的问题,请参考以下文章

介绍Spring Cloud微服务架构

Dubbo和Spring Cloud微服务架构‘

Dubbo和Spring Cloud微服务架构对比

介绍一下Spring Cloud微服务架构的核心特性

Dubbo 和 Spring Cloud微服务架构 比较及相关差异

Spring Cloud构建微服务架构-创建“服务提供方”