微服务学习笔记五 Spring Cloud 服务消费者及服务网关

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
注册配置 MSE Nacos/ZooKeeper,118元/月
云原生网关 MSE Higress,422元/月
简介: 微服务学习笔记五 Spring Cloud 服务消费者及服务网关

## 服务消费者 consumer

创建maven工程,pom.xml


```java

<dependencies>

   <dependency>

       <groupId>org.springframework.cloud</groupId>

       <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>

       <version>2.0.2.RELEASE</version>

   </dependency>

</dependencies>

```


创建配置文件,application.yml


```java

server:

 port: 8020

spring:

 application:

   name: consumer

eureka:

 client:

   service-url:

     defaultZone: http://localhost:8761/eureka/

 instance:

   prefer-ip-address: true

```


创建启动类


```java

package com.shuang;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class ConsumerApplication {

   public static void main(String[] args) {

       SpringApplication.run(ConsumerApplication.class,args);

   }

   @Bean

public RestTemplate restTemplate(){

   return new RestTemplate();

}

}

```


Handler


```java

package com.shuang.controller;


import com.shuang.entity.Student;

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

import org.springframework.web.bind.annotation.*;

import org.springframework.web.client.RestTemplate;


import java.util.Collection;


@RestController

@RequestMapping("/consumer")

public class ConsumerHandler {

   @Autowired

   private RestTemplate restTemplate;


   @GetMapping("/findAll")

   public Collection<Student> findAll(){

       return restTemplate.getForEntity("http://localhost:8010/student/findAll",Collection.class).getBody();

   }

   @GetMapping("/findAll2")

   public Collection<Student> findAll2(){

       return restTemplate.getForObject("http://localhost:8010/student/findAll",Collection.class);

   }


   @GetMapping("/findById/{id}")

   public Student findById(@PathVariable("id") long id){

       return restTemplate.getForEntity("http://localhost:8010/student/findById/{id}",Student.class,id).getBody();

   }


   @GetMapping("/findById2/{id}")

   public Student findById2(@PathVariable("id") long id){

       return restTemplate.getForObject("http://localhost:8010/student/findById/{id}",Student.class,id);

   }


   @PostMapping("save")

   public void save(@RequestBody Student student){

       restTemplate.postForEntity("http://localhost:8010/student/save",student,null).getBody();

   }

   @PostMapping("/save2")

   public void save2(@RequestBody Student student){

       restTemplate.postForObject("http://localhost:8010/student/save",student,null);


   }


   @PutMapping("/update")

   public void update(@RequestBody Student student){

       restTemplate.put("http://localhost:8010/student/update",student);

   }


   @DeleteMapping("/deleteById/{id}")

   public void deleteById(@PathVariable("id") long id){

       restTemplate.delete("http://localhost:8010/student/deleteById/{id}",id);

   }


}

```


## 服务网关:

![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/20200624123233579.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0OTY5NjQz,size_16,color_FFFFFF,t_70)

Spring Cloud 集成了 Zuul组件,实现服务网关

Zuul是Netflix提供的一个开源的API网关服务器,是客户端和网站后端所有请求

的中间层,对外开放一个API,将所有请求导入统一的入口,屏蔽了服务端的具体

实现逻辑,Zuul可以实现反向代理的功能,在网关内部实现动态路由、身份认证、

IP过滤、数据监控等。

创建Maven工程,pom.xml


```java

<dependencies>

   <dependency>

       <groupId>org.springframework.cloud</groupId>

       <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>

       <version>2.0.2.RELEASE</version>

   </dependency>


   <dependency>

       <groupId>org.springframework.cloud</groupId>

       <artifactId>spring-cloud-starter-netflix-zuul</artifactId>

       <version>2.0.2.RELEASE</version>

   </dependency>

</dependencies>

```


创建配置文件。application.yml


```java

server:

 port: 8030

spring:

 application:

   name: gateway

eureka:

 client:

   service-url:

     defaultZone: http://localhost:8761/eureka/

zuul:

 routes:

   provider: /p/**

```


属性说明:

zuul.routers.provider:给服务提供者provider设置映射


创建启动类


```java

package com.shuang;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.cloud.netflix.zuul.EnableZuulProxy;


@EnableZuulProxy

@EnableAutoConfiguration

public class ZuulApplication {

   public static void main(String[] args) {

       SpringApplication.run(ZuulApplication.class,args);

   }

}

```


注解说明:

EnableZuulProxy:包含了EnableZuulServer,设置该类是网关的启动类。

EnableAutoConfiguretion:可以帮助Spring Boot应用将所有符合条件的

Configuration配置加载到当前Spring Boot创建并使用的IOC容器中。


Zuul自带了负载均衡功能,修改provider的代码


```java

package com.shuang.controller;



import com.shuang.entity.Student;

import com.shuang.repository.StudentRepository;

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

import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.*;


import java.util.Collection;


@RestController

@RequestMapping("/student")

public class StudentHandler {

   @Autowired

   private StudentRepository studentRepository;


   @Value("${server.port}")

   private String port;


   @GetMapping("/findAll")

   public Collection<Student> findAll(){

       return studentRepository.findAll();

   }

   @GetMapping("/findById/{id}")

   public Student findById(@PathVariable("id") long id){

       return studentRepository.findById(id);

   }

   @PostMapping("/save")

   public void save(@RequestBody Student student){

       studentRepository.saveOrUpdate(student);

   }

   @PutMapping("/update")

   public void update(@RequestBody Student student){

       studentRepository.saveOrUpdate(student);

   }

   @DeleteMapping("/deleteById/{id}")

   public void deleteById(@PathVariable("id") long id){

       studentRepository.deleteById(id);

   }


   @GetMapping("/index")

   public String index(){

       return "当前的端口: "+this.port;

   }

}

```


启动eurekaclient的启动类。修改端口,增加另外一个启动类,启动(相当于两个相同服务提供者)

在Zuul中访问:两个服务提供者轮流提供服务

![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/20200624123408289.png)

![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/20200624123423690.png)






目录
相关文章
|
1天前
|
Java 微服务 Spring
SpringBoot+Vue+Spring Cloud Alibaba 实现大型电商系统【分布式微服务实现】
文章介绍了如何利用Spring Cloud Alibaba快速构建大型电商系统的分布式微服务,包括服务限流降级等主要功能的实现,并通过注解和配置简化了Spring Cloud应用的接入和搭建过程。
SpringBoot+Vue+Spring Cloud Alibaba 实现大型电商系统【分布式微服务实现】
|
1天前
|
Java API 微服务
服务网关Gateway
该博客文章详细介绍了Spring Cloud Gateway的使用方法和概念。文章首先阐述了API网关在微服务架构中的重要性,解释了客户端直接与微服务通信可能带来的问题。接着,文章通过具体的示例代码,展示了如何在Spring Cloud Gateway中添加依赖、编写路由规则,并对路由规则中的基本概念如Route、Predicate和Filter进行了详细解释。最后,文章还提供了路由规则的测试方法。
服务网关Gateway
|
17天前
|
消息中间件 监控 Java
解锁Spring Cloud微服务架构的奥秘:深度剖析拆分原则,打造高内聚低耦合的业务创新引擎!
【8月更文挑战第3天】踏入微服务领域,Spring Cloud以丰富组件助力高效系统构建。微服务拆分需遵循原则确保系统高内聚低耦合且能适应变化。首要原则为单一职责,每个服务专注一个业务功能,降低复杂度并提高可维护性。其次,追求高内聚低耦合以减少服务间影响。围绕业务域拆分有助于保持逻辑清晰及团队协作。处理数据一致性问题时,考虑采用最终一致性模型。Spring Cloud提供Eureka、Zuul/Gateway、Sleuth和Config等工具支持服务发现、路由、跟踪及配置管理,共同构建灵活健壮的微服务架构。
33 2
|
17天前
|
NoSQL Java Redis
Spring Boot集成Redis全攻略:高效数据存取,打造性能飞跃的Java微服务应用!
【8月更文挑战第3天】Spring Boot是备受欢迎的微服务框架,以其快速开发与轻量特性著称。结合高性能键值数据库Redis,可显著增强应用性能。集成步骤包括:添加`spring-boot-starter-data-redis`依赖,配置Redis服务器参数,注入`RedisTemplate`或`StringRedisTemplate`进行数据操作。这种集成方案适用于缓存、高并发等场景,有效提升数据处理效率。
72 2
|
13天前
|
监控 供应链 安全
构建高效微服务架构:API网关与服务熔断策略
【7月更文挑战第38天】随着现代应用程序向微服务架构的转型,系统的稳定性和效率成为了开发团队关注的焦点。本文将探讨在微服务环境中实现系统可靠性的关键组件——API网关,以及如何在服务间通讯时采用熔断机制来防止故障蔓延。通过分析API网关的核心功能和设计原则,并结合熔断策略的最佳实践,我们旨在提供一套提高分布式系统弹性的策略。
|
14天前
|
负载均衡 Java 应用服务中间件
Gateway服务网关
本节针对微服务中另一重要组件:网关 进行了实战性演练,网关作为分布式架构中的重要中间件,不仅承担着路由分发(重点关注Path规则配置),同时可根据自身负载均衡策略,对多个注册服务实例进行均衡调用。本节我们借助GateWay实现的网关只是技术实现的方案之一,后续大家可能会接触像:Zuul、Kong等,其实现细节或有差异,但整体目标是一致的。
|
3天前
|
监控 负载均衡 API
从单体到微服务:架构转型之道
【8月更文挑战第17天】从单体架构到微服务架构的转型是一项复杂而系统的工程,需要综合考虑技术、团队、文化等多个方面的因素。通过合理的规划和实施策略,可以克服转型过程中的挑战,实现系统架构的升级和优化。微服务架构以其高度的模块化、可扩展性和灵活性,为业务的持续发展和创新提供了坚实的技术保障。
|
13天前
|
缓存 监控 API
【微服务战场上的神秘守门人】:揭秘API网关的超能力 —— 探索微服务架构中的终极守护者与它的神奇魔法!
【8月更文挑战第7天】随着微服务架构的流行,企业应用被拆分为围绕特定业务功能构建的小型服务。API网关作为微服务间的通信管理核心,对请求进行路由、认证、限流等处理,简化客户端集成并提升用户体验。以电商应用为例,通过Kong部署API网关,配置产品目录等服务的API及JWT认证插件,确保安全高效的数据交互。这种方式不仅增强了系统的可维护性和扩展性,还提供了额外的安全保障。
31 2
|
21天前
|
负载均衡 监控 API
探索微服务架构中的API网关模式
【7月更文挑战第30天】在微服务架构的复杂网络中,API网关扮演着交通枢纽的角色,不仅简化了客户端与各微服务的交互,还提升了系统的安全性和可维护性。本文将深入探讨API网关的设计原则、核心功能以及在实际应用中的部署策略,旨在为后端开发者提供一套完整的API网关解决方案。

热门文章

最新文章