600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > Spring Cloud【Finchley】-01服务提供者与服务消费者

Spring Cloud【Finchley】-01服务提供者与服务消费者

时间:2019-08-15 01:44:37

相关推荐

Spring Cloud【Finchley】-01服务提供者与服务消费者

文章目录

Spring Cloud总览概述示例场景描述用户微服务新建Spring Boot服务项目结构用户库表ModelDao层ServiceController 暴露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="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /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><!-- /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@Datapublic 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;@Repositorypublic 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;@RestControllerpublic 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: 7900spring:jpa:generate-ddl: falseshow-sql: truehibernate:ddl-auto: nonedatasource:platform: h2schema: classpath:schema.sqldata: classpath:data.sqllogging: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;@SpringBootApplicationpublic class MicorserviceSimpleProviderUserApplication {public static void main(String[] args) {SpringApplication.run(MicorserviceSimpleProviderUserApplication.class, args);}}

右键–Run As --Spring Boot App,启动成功后

访问数据库中存在的用户

http://localhost:7900/user/1

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

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

{"id":null,"username":null,"name":"no this user","age":null,"balance":null}

电影微服务

新建Spring Boot服务

如用户微服务,只不过我们这里仅仅作为消费者,仅使用web即可。

项目结构

pom.xml

<?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /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><!-- /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;@RestControllerpublic 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;@Datapublic 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;@SpringBootApplicationpublic class MicorserviceSimpleConsumerMovieApplication {@Beanpublic RestTemplate restTemplate(){return new RestTemplate();}public static void main(String[] args) {SpringApplication.run(MicorserviceSimpleConsumerMovieApplication.class, args);}}

配置文件 application.yml

配置端口及用户微服务的地址

server:port: 7901user: userServicePath: http://localhost:7900/user/

测试

启动用户微服务,访问7901

访问数据库中存在的用户

http://localhost:7901/movie/1

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

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

{"id":null,"username":null,"name":"no this user","age":null,"balance":null}

成功调用到了用户微服务对外提供的服务。

示例的缺点

不难发现,虽然我们把用户微服务对外提供的接口地址配置在了配置文件中,然后通过@Value的方式去加载该属性,但是一旦用户微服务修改了地址,电影微服务作为消费者也要修改对应的地址,多了的话,也是很难管理

第二个原因,如果存在多个用户微服务,如何进行负载? nginx固然可以,如果这种服务比较多,依赖nginx, 增加节点还是需要修改nginx配置文件,比较头疼

所以 接下来我们来看下服务发现与服务注册,这里主要说的是Spring Cloud支持比较好的Eureka

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。