Spring Cloud service provider and service consumer

【Video & Communication Platform】

à Spring Cloud Video 

http://study.163.com/course/introduction.htm?courseId=1004638001

à Spring Boot communication platform 

http://412887952-qq-com.iteye.com/blog/2321532

 

The two most basic roles in microservices are service provider and service consumer .

When all the code was in the same framework before, for example, if the Controller called the Service , it could be called by directly injecting the Service bean . Now that microservices are made, then we need to have a project dedicated to providing corresponding service functions, and corresponding project consumption functions. This is the most basic concept of service providers and service consumers. Well, today we will learn from actual combat.

Outline of this section:

wrote
(1) Concept of service provider and service consumer
(2) Coding ideas
(3) Service provider coding
(4) Service consumer coding
(5) Problems

 

Next, look at the specific content:

( 1 ) Concept of service provider and service consumer

Service Provider : The callee of a service (i.e. a service that provides services to other services);

Service consumers : callers of services (i.e. services that depend on other services);

 

( 2 ) Coding ideas

Here we use the most basic way to implement service providers and service consumers.

( 1 ) Two projects, one service provider and one service consumer;

( 2 ) The service provider queries data from the in-memory database H2 , and the Controller makes a call to obtain it;

( 3 ) The service consumer calls the service provider's Controller to obtain data, and then returns it to the browser.

 

( 3 ) Service Provider Code

àNew construction

Create a new project that provides user information and name it: microservie-provider-user

 

àAdd dependency package in pom.xml

 

<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.kfit</groupId>
    <artifactId>ms-provider-user</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>ms-provider-user</name>
    <url>http://maven.apache.org</url>
 
    <!-- spring boot parent节点,引入这个之后,在下面和spring boot相关的就不需要引入版本了; -->
    <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>1.4.1.RELEASE</version>
    </parent>
 
    <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
 
    <dependencies>
       <!-- web支持: 1、web mvc; 2、restful; 3、jackjson支持; 4、aop ........ -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
 
       <!-- 内存数据库h2 -->
       <dependency>
           <groupId>com.h2database</groupId>
           <artifactId>h2</artifactId>
           <scope>runtime</scope>
       </dependency>
 
       <!-- spring data jpa -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-jpa</artifactId>
       </dependency>
    </dependencies>
</project>
 

 

 

àsrc/main/resources下新建schema.sql添加建表语句

      创建了一张User表:

 

drop table user if exists;
create table user(
    id bigint generated bydefaultas identity,
    username varchar(40),
    name varchar(20),
    age int(3),
    balance decimal(10,2),
    primarykey(id)
);
 
 

 

 

àsrc/main/resources/新建data.sql插入数据

      User表插入几条数据进行测试:

 

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);
 

 

 

à创建实体类User

 

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Entity
public class User implements Serializable{
    private static final long serialVersionUID = 1L;
    @Id@GeneratedValue
    private long id; //主键.
    private String username;//用户名.
    private String name; //姓名
    private int age; //年龄.
    private BigDecimal balance;//余额.
   
}
 

 

      为什么要加@JsonIgnoreProperties呢?

问题在于,使用load方法,您只需要一个代理,而不是真正的对象。代理对象没有已经加载的属性,所以当序列化发生时,没有要序列化的属性。使用get方法,您实际上可以获得真正的对象,这个对象实际上可以被序列化。

      具体可以参考文章:https://my.oschina.net/lieefu/blog/680098

 

à创建DaoUserRepository

 

public interface UserRepository extends JpaRepository<User,Long>{
 
}
 

 

 

à创建ServiceUserService

 

@Service
public class UserService {
   
    @Autowired
    private UserRepository userRepository;
   
    public User getById(longid){
       return userRepository.getOne(id);
    }
}
 

 

 

à创建ControllerUserController

 

@RestController
public class UserController {
    @Autowired
    private UserService userService;
   
    @GetMapping("/user/{id}")
    public User getById(@PathVariablelongid){
       User user = userService.getById(id);
       System.out.println(user);
       return user;
    }
}
 

 

 

àsrc/main/resources新建application.properties

主要是配置端口号和jpa配置:

 

server.port=7900
 
spring.jpa.generate-ddl=false
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.datasource.platform=h2
spring.datasource.schema=classpath:schema.sql
spring.datasource.data=classpath:data.sql
 
logging.level.root=INFO
logging.level.org.hibernate=INFO
 

 

 

à编写启动类

 

@SpringBootApplication
public class App {
    public staticv oid main(String[] args) {
       SpringApplication.run(App.class, args);
    }
}
 

 

 

à启动App测试

启动访问:http://127.0.0.1:7900/user/1 可以在浏览器中看到返回信息:

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

 

      到此服务提供者就编写完毕了,这个代码没有什么特别之处,和我们常规代码编写是一样的!。

 

4)服务消费者编码

à新建工程

      新建一个服务消费者项目,取名为:microservice-consumer-movice

àpom.xml添加依赖包

 

<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.kfit</groupId>
  <artifactId>ms-consumer-movice</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
 
  <name>ms-consumer-movice</name>
  <url>http://maven.apache.org</url>
 
    <!-- spring boot parent节点,引入这个之后,在下面和spring boot相关的就不需要引入版本了; -->
    <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>1.5.8.RELEASE</version>
    </parent>
 
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
 
  <dependencies>
     <!-- web支持: 1、web mvc; 2、restful; 3、jackjson支持; 4、aop ........ -->
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>
</project>
 

 

 

à新建实体类User

public class User implements Serializable{
    private static final longserialVersionUID = 1L;
    private long id; //主键.
    private String username;//用户名.
    private String name; //姓名
    private int age; //年龄.
    private BigDecimal balance;//余额.
   
}

 

 

à新建ControllerMoviceController

@RestController
public class MoviceController {
   
    @Autowired
    private RestTemplate restTemplate;
   
    @GetMapping("/user/{id}")
    public User getById(longid){
       String url = "http://127.0.0.1:7900/user/"+id;
       return restTemplate.getForObject(url, User.class);
    }
}

 

 

àsrc/main/resources新建application.properties

这里只配置了端口号:

server.port=7901

 

à新建启动类App.java

@SpringBootApplication
public class App {
   
    @Bean
    public RestTemplate restTemplate(){
       returnnew RestTemplate();
    }
   
    publicstaticvoid main(String[] args) {
       SpringApplication.run(App.class, args);
    }
}

 

这里将RestTemplate进行初始化,交给Spring进行管理。

à启动测试

      启动访问:http://127.0.0.1:7901/user/2 ,返回给浏览器信息:

{"id":2,"username":"user2","name":"李四","age":20,"balance":100.00}

 

 

5)存在问题

      此例子简单易理解,但是存在很多的问题,比如:

1)请求地址(http://127.0.0.1:7900/user/)硬编码了;

2)当有多个提供者节点的时候,怎么进行负载,基本想法可以在提供者和消费者中间加一个反向代理,但是服务太多的时候不利于管理。

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326505160&siteId=291194637