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

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介: 微服务学习笔记五 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)






目录
相关文章
|
21小时前
|
负载均衡 Java 网络架构
在SpringCloud2023中快速集成SpringCloudGateway网关
本文主要简单介绍SpringCloud2023实战中SpringCoudGateway的搭建。后续的文章将会介绍在微服务中使用熔断Sentinel、鉴权OAuth2、SSO等技术。
36 2
在SpringCloud2023中快速集成SpringCloudGateway网关
|
21小时前
|
JavaScript 前端开发 网络协议
KOI 微服务提供者接收请求,提供服务并传回给 Orchestra
KOI 微服务提供者接收请求,提供服务并传回给 Orchestra
4 0
|
21小时前
|
监控 安全 Java
Spring cloud原理详解
Spring cloud原理详解
17 0
|
21小时前
|
消息中间件 负载均衡 Java
【Spring Cloud 初探幽】
【Spring Cloud 初探幽】
16 1
|
21小时前
|
安全 Java Docker
|
21小时前
|
Java 开发者 微服务
Spring Cloud原理详解
【5月更文挑战第4天】Spring Cloud是Spring生态系统中的微服务框架,包含配置管理、服务发现、断路器、API网关等工具,简化分布式系统开发。核心组件如Eureka(服务发现)、Config Server(配置中心)、Ribbon(负载均衡)、Hystrix(断路器)、Zuul(API网关)等。本文讨论了Spring Cloud的基本概念、核心组件、常见问题及解决策略,并提供代码示例,帮助开发者更好地理解和实践微服务架构。此外,还涵盖了服务通信方式、安全性、性能优化、自动化部署、服务网格和无服务器架构的融合等话题,揭示了微服务架构的未来趋势。
35 6
|
21小时前
|
负载均衡 Java API
构建高效微服务架构:API网关与服务熔断策略
【5月更文挑战第2天】 在微服务架构中,确保系统的高可用性与灵活性是至关重要的。本文将深入探讨如何通过实施有效的API网关和设计合理的服务熔断机制来提升分布式系统的鲁棒性。我们将分析API网关的核心职责,包括请求路由、负载均衡、认证授权以及限流控制,并讨论如何利用熔断器模式防止故障传播,维护系统的整体稳定性。文章还将介绍一些实用的技术和工具,如Netflix Zuul、Spring Cloud Gateway以及Hystrix,以帮助开发者构建一个可靠且高效的微服务环境。
|
21小时前
|
JSON Java Apache
Spring Cloud Feign 使用Apache的HTTP Client替换Feign原生httpclient
Spring Cloud Feign 使用Apache的HTTP Client替换Feign原生httpclient
|
21小时前
|
负载均衡 Java 开发者
Spring Cloud:一文读懂其原理与架构
Spring Cloud 是一套微服务解决方案,它整合了Netflix公司的多个开源框架,简化了分布式系统开发。Spring Cloud 提供了服务注册与发现、配置中心、消息总线、负载均衡、熔断机制等工具,让开发者可以快速地构建一些常见的微服务架构。
|
21小时前
|
Java Docker 微服务