SpringCloud初体验(不断更新中,包含源码)

SpringCloud初体验(不断更新中)


前言

源码地址:github源码传送门

SpringCloud入门最佳实践之一


话不多说,上实例

一、SpringCloud是什么?

微服务架构集大成者,云计算最佳业务实践。Spring Cloud是一系列框架的有序集合,它利用Spring Boot简化了分布式系统的开发,如服务治理、服务发现、网关、路由、链路追踪、监控等。Spring Cloud是将应用广泛的模块进行了有机结合,封装,极大的减少了各模块的开发成本。

优点:

包含了微服务架构的大部分功能。
约定优于配置,基于注解,没有配置文件。
轻量级组件,Spring Cloud整合的组件大多比较轻量级,且都是各自领域的佼佼者。
开发简便,Spring Cloud对各个组件进行了大量的封装,从而简化了开发。
开发灵活,Spring Cloud的组件都是解耦的,开发人员可以灵活按需选择组件。

缺点:

项目结构复杂,每一个组件或者每一个服务都需要创建一个项目。对于后期维护来说需要付出一定的工作量。

二、开始

1.创建maven父项目

在sts中选择创建maven project,各项设置如下,Group Id为包名,ArtifactId为工程名称,打包类型是pom:
在这里插入图片描述
pom文件中添加springboot依赖。

<parent>
  	<groupId>org.springframework.boot</groupId>
  	<artifactId>spring-boot-starter-parent</artifactId>
  	<version>2.0.2.RELEASE</version>
  </parent>

定义应用Spring Cloud的版本

<properties>
  	<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
</properties>

增加全局依赖

<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-dependencies</artifactId>
			<version>${spring-cloud.version}</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>

2.创建EurekaServer工程

Eureka分为服务端和客户端。服务端,作为注册中心,用于提供服务治理、服务发现等功能;客户端,用于向EurekaServer注册服务并可从EurekaServer获取需要调用的服务地址信息;在上面创建的父项目中,创建MavenModule项目:在这里插入图片描述在这里插入图片描述

pom文件中增加相关依赖:

<dependencies>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
</dependencies>

创建启动类EurekaServerDemoApplication:

package com.cdsn.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(EurekaServerDemoApplication.class, args);
	}

}

创建application.yml文件:

spring:
  application:
    name: eureka-server
server:
  port: 9000
  
eureka:
  client: 
    register-with-eureka: true  #false:不作为一个客户端注册到注册中心,是否将自身的实例信息注册到eureka服务器
    fetch-registry: false      #是否从eurekaserver获取注册信息,单节点,无需从其他server获取
    instance-info-replication-interval-seconds: 10 
    registry-fetch-interval-seconds: 30  #从eureka服务端获取注册信息的间隔时间
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
  instance:
    hostname: localhost

启动项目,并用浏览器打开后效果如下:
在这里插入图片描述

3.创建网关工程

Spring Cloud Gateway是 Spring 官方基于Spring 5.0,Spring Boot 2.0 和 Project Reactor等技术开发的网关,旨在为微服务架构提供一种简单而有效的统一的API路由管理方式,统一访问接口。Spring Cloud Gateway 作为 Spring Cloud 生态系中的网关,目标是替代 Netflix ZUUL,其不仅提供统一的路由方式,并且基于 Filter 链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。它是基于Nttey的响应式开发模式。SpringCloud Gateway是整个框架请求的入口。

  1. 路由(route) 路由是网关最基础的部分,路由信息由一个ID、一个目的URL、一组断言工厂和一组Filter组成。如果断言为真,则说明请求URL和配置的路由匹配。
  2. 断言/谓词(predicates) Java8中的断言函数,Spring Cloud Gateway中的断言函数输入类型是Spring5.0框架中的ServerWebExchange。Spring Cloud Gateway中的断言函数允许开发者去定义匹配来自Http Request中的任何信息,比如请求头和参数等。
  3. 过滤器(filter) 一个标准的Spring webFilter,Spring Cloud Gateway中的Filter分为两种类型,分别是Gateway Filter和Global Filter。过滤器Filter可以对请求和响应进行处理。
    关于谓词,可参考这两篇文章:
    谓词说明1
    谓词说明2

注意 SpringCloud Gateway使用的web框架为webflux,和SpringMVC不兼容。引入的限流组件是hystrix。redis底层不再使用jedis,而是lettuce。
在这里插入图片描述
pom文件添加maven依赖:

<dependencies>
  	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
		<!-- 移除tomcat容器 -->
		<exclusions>
			<exclusion>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-tomcat</artifactId>
			</exclusion>
		</exclusions>
	</dependency>
	
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-webflux</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-gateway</artifactId>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-actuator</artifactId>
	</dependency>


	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
	</dependency>
 </dependencies>

创建启动类GatewayDemoApplication.java:

package com.csdn.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
@EnableCircuitBreaker
public class GatewayDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(GatewayDemoApplication.class, args);
	}

}

注:@EnableDiscoveryClient和@EnableEurekaClient的区别:前者可以被
zookeeper、consul、eureka等发现,后者专门针对eureka。

创建application.yml配置文件:

server:
  port: 8080

spring:
  application:
    name: springcloud-gateway
  mvc:
    servlet:
      load-on-startup: 1
  servlet:
    multipart:
      max-request-size: 100MB #最大请求大小
      max-file-size: 100MB #最大文件大小
  cloud:
    gateway:
      routes:
        - id: gatewaytest #自定义的路由 ID,保持唯一
          uri: lb://feign-consumer-demo ##在uri的schema协议部分为自定义的lb:类型,表示从微服务注册中心(如Eureka)订阅服务,并且进行服务的路由
          predicates: ##注意谓词下面的横杠
          - Path=/consumer/**
          filters: 
          - StripPrefix=1 #去掉Path前缀,参数为1代表去掉/consumer

#eureka client 配置
eureka:
  client:
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:9000/eureka/
  instance:
    hostname: localhost

在这里插入图片描述

4.创建服务提供者provider-demo

创建mavenmodul项目
在这里插入图片描述
pom文件中引入相关依赖。

<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>
  <parent>
    <groupId>com.csdn.cloud</groupId>
    <artifactId>springcloud-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>provider-demo</artifactId>
  
  <dependencies>
  	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>

	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
	</dependency>
  </dependencies>
</project>

创建配置文件:

server:
  port: 9001

spring:
  application:
    name: provider-demo
  mvc:
    servlet:
      load-on-startup: 1
  servlet:
    multipart:
      max-request-size: 100MB #最大请求大小
      max-file-size: 100MB #最大文件大小
      
#eureka client 配置
eureka:
  client:
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:9000/eureka/
  instance:
    hostname: localhost

创建启动类ProviderDemo.java:

package com.csdn.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
public class ProviderDemo {

	public static void main(String[] args) {
		SpringApplication.run(ProviderDemo.class, args);
	}

}

创建ProviderUserInfoController,供消费者调用:

package com.csdn.cloud.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/provider")
public class ProviderUserInfoController {

	@RequestMapping("/getUserInfo")
	public Object getUserInfo(@RequestParam("userId") String userId) {
		Map<String,String> map = new HashMap<String, String>();
		map.put("id", userId);
		map.put("userName", "越");
		map.put("gender", "女");
		return map;
	}
}

启动后,在Eureka端可以看到:
在这里插入图片描述

5.创建服务消费者feign-consumer-demo

Feign是Netflix公司开源的轻量级rest客户端,Feign采用声明式调用。Spring Cloud引入Feign并且集成了Ribbon实现客户端负载均衡调用。与Ribbon功能类似,同时进行客户端负载均衡的处理;不过它能提供类似本地调用的方式调用远程的EurekaClient提供的服务,即:声明式调用;它实际上是在Ribbon基础上进行了进一步的封装来提高调用服务的简便性。
在这里插入图片描述pom文件依赖:

<dependencies>
  	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>

	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
	</dependency>
       
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-openfeign</artifactId>
	</dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-actuator</artifactId>
       </dependency>
       
   </dependencies>

添加yml配置文件:

server:
  port: 9002
spring:
  application:
    name: feign-consumer-demo
    
    
eureka:
  client:
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:9000/eureka/
  instance:
    hostname: localhost   

创建启动入口FeignConsumerApplication.java:

package com.csdn.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class FeignConsumerApplication {

	public static void main(String[] args) {
		SpringApplication.run(FeignConsumerApplication.class, args);
	}
}

创建FeignClient接口ProviderInterface.java:

package com.csdn.cloud.interfaces;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value="provider-demo")
public interface ProviderInterface {

	@GetMapping("/provider/getUserInfo")
	public Object getUserInfo(@RequestParam("userId") String userId);
}

创建Controller,通过Feign,声明书调用服务提供者UserInfoController.java。

package com.csdn.cloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.csdn.cloud.interfaces.ProviderInterface;

@RestController
public class UserInfoController {
	
	@Autowired
	private ProviderInterface providerInterface;
	
	@RequestMapping(value="/getUserInfo/{userId}",method= {RequestMethod.GET})
	public Object getUserInfo(@PathVariable String userId) {
		System.out.println(userId);
		return providerInterface.getUserInfo(userId);
	}
}

启动后如图:
在这里插入图片描述

5.测试

打开浏览器,输入测试链接:
http://192.168.1.117:8080/consumer/getUserInfo/123
结果如图所示:
在这里插入图片描述


总结

数据流程如图:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值