天天看点

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、应用发生故障,如何能够进行问题追踪快速定位?

继续阅读