二十五、SpringBoot之分布式(Zookeeper和Dubbo、SpringBoot和SpringCloud)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29479041/article/details/83549898

一、分布式应用

在分布式系统中,国内常用zookeeper+dubbo组合,而SpringBoot推荐使用全栈的Spring,SpringBoot+SpringCloud。

分布式系统:

  • 单一应用架构

当网站流量很小时,只需一个应用,将所有功能都部署在一起,以减少部署节点和成本。此时,用于简化增删改查工作量的数据访问框架(ORM)是关键。

  • 垂直应用架构

当访问量逐渐增大,单一应用增加机器带来的加速度越来越小,将应用拆成互不相干的几个应用,以提升效率。此时,用于加速前端页面开发的Web框架(MVC)是关键。

  • 分布式服务架构

当垂直应用越来越多,应用之间交互不可避免,将核心业务抽取出来,作为独立的服务,逐渐形成稳定的服务中心,使前端应用能更快速的响应多变的市场需求。此时, 用于提高业务复用及整合的分布式服务框架(RPC)是关键。

  • 流动计算架构

当服务越来越多,容量的评估,小服务资源的浪费等问题逐渐显现,此时需增加一个调度中心基于访问压力实时管理集群容量,提高集群利用率。此时,用于提高机器利用率的资源调度和治理中心(SOA)是关键。

二、Zookeeper和Dubbo

  • ZooKeeper

ZooKeeper 是一个分布式的,开放源码的分布式应用程序协调服务。它是 一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护、 域名服务、分布式同步、组服务等。

  • Dubbo

Dubbo是Alibaba开源的分布式服务框架,它最大的特点是按照分层的方式来架构,使用这种方式可以使各个层之间解耦合(或者最大限度地松耦合)。从服务模型的角度来看,Dubbo采用的是一种非常简单的模型,要么是提供方提供服务,要么是消费方消费服务,所以基于这一点可以抽象出服务提供方(Provider)和服务消费方(Consumer)两个角色。

dubbo文档

1、将服务提供者注册到注册中心

  • 1.引入dubbo和zkclient相关依赖
        <!-- 引入dubbo -->
        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>0.1.0</version>
        </dependency>
        <!-- 引入zookeeoer的客户端工具 -->
        <dependency>
            <groupId>com.github.sgroschupf</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.1</version>
        </dependency>
  • 2.配置dubbo的扫描包和注册中心地址
dubbo.application.name=provider-ticket
dubbo.registry.address=zookeeper://192.168.3.226:2181
dubbo.scan.base-packages=com.atguigu.ticket.service
  • 3.使用@Service 发布服务
package com.atguigu.ticket.service;

public interface TicketService {
    public String getTicket();
}


package com.atguigu.ticket.service;

import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;

@Component
@Service //将服务发布出去
public class TicketServiceImpl implements TicketService{
    @Override
    public String getTicket() {
        return "《hahaha》";
    }
}

2、将服务消费者注册到注册中心

  • 1.引入dubbo和zkclient相关依赖
        <!-- 引入dubbo -->
        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>0.2.0</version>
        </dependency>
        <!-- 引入zookeeoer的客户端工具 -->
        <dependency>
            <groupId>com.github.sgroschupf</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.1</version>
        </dependency>
  • 2.配置dubbo的扫描包和注册中心地址
dubbo.application.name=consumer-user
dubbo.registry.address=zookeeper://192.168.3.227:2182
  • 3.引用服务
package com.atguigu.ticket.service;

public interface TicketService {
    public String getTicket();
}

package com.atguigu.user.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.ticket.service.TicketService;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Reference
    TicketService ticketService;
    public void hello(){
       String ticket = ticketService.getTicket();
       System.out.println("买到票拉"+ticket);
    }
}

3、遇到一个问题没有解决:'消费方'注解引用'提供方'的接口时报空指针

java.lang.NullPointerException
	at com.atguigu.user.service.UserService.hello(UserService.java:13)
	at com.atguigu.user.ConsumerUserApplicationTests.contextLoads(ConsumerUserApplicationTests.java:18)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
	at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
	at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
	at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
	at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

三、SpringBoot和SpringCloud

1、SpringCloud

SpringCloud是一个分布式的整体解决方案。SpringCloud 为开发者提供了在分布式系统(配 置管理,服务发现,熔断,路由,微代理,控制总线,一次性token,全局琐,leader选举,分 布式session,集群状态)中快速构建的工具,使用SpringCloud的开发者可以快速的启动服务或构建应用、同时能够快速和云平台资源进行对接。

SpringCloud分布式开发五大常用组件

  • 服务发现——Netflix Eureka
  • 客服端负载均衡——Netflix Ribbon
  • 断路器——Netflix Hystrix
  • 服务网关——Netflix Zuul
  • 分布式配置——Spring Cloud Config

2、微服务

Martin Fowler 微服务原文

3、SpringCloud 入门

  • 1.创建注册中心

/**
* 1、引入eureka
* 2、配置Eureka信息
* 3、@EnableEurekaServer  //启用注册中心的功能
* */

pom.xml

                <!-- 引入eureka -->
                <dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
		</dependency>

application.yml

# 配置Eureka信息
server:
  port: 8761
eureka:
  instance:
    hostname: eureka-server # eureka实例的主机名
  client:
    register-with-eureka: false #不把自己注册到eureka上
    fetch-registry: false #不从eureka上来获取服务到注册信息
    service-url:
      defaultZone: http://localhost:8761/eureka/

EurekaServerApplication

//启用注册中心的功能
@EnableEurekaServer  
@SpringBootApplication
public class EurekaServerApplication {
	public static void main(String[] args) {
		SpringApplication.run(EurekaServerApplication.class, args);
	}
}

运行测试:http://localhost:8761/

  • 2.创建provider

/**
* 1、引入eureka-client
* 2、配置Eureka信息
* 3、写service和control并运行,将服务注册进注册中心
* */

pom.xml

                <!-- 引入eureka-client -->                
                <dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
                <!-- 引入web -->               
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

application.yml

server:
  port: 8002
spring:
  application:
    name: provider-ticket
eureka:
  instance:
    prefer-ip-address: true #注册服务的时候使用服务的ip地址
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka

Service

@Service
public class TicketService {
    public String getTicket(){
        System.out.println("8002");
        return "<斗牛>";
    }
}

Controller

@RestController
public class TicketController {
    @Autowired
    TicketService ticketService;
    @GetMapping("/ticket")
    public  String getTicket(){
        return ticketService.getTicket();
    }
}

运行测试结果

  • 3.创建consumer

/**
* 1、引入eureka-client
* 2、配置Eureka信息
* 3、@EnableDiscoveryClient //开启发现服务功能
* 4、使用RestTemplate 发送http请求的
* 5、@LoadBalanced //使用负载均衡机制
* */

pom.xml

                <!-- 引入eureka-client -->                
                <dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
                <!-- 引入web -->               
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

application.yml

server:
  port: 8200
spring:
  application:
    name: consumer-user
eureka:
  instance:
    prefer-ip-address: true #注册服务的时候使用服务的ip地址
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka

ConsumerUserApplication

@EnableDiscoveryClient //开启发现服务功能
@SpringBootApplication
public class ConsumerUserApplication {
	public static void main(String[] args) {
		SpringApplication.run(ConsumerUserApplication.class, args);
	}

	//发送http请求的
	@LoadBalanced //使用负载均衡机制
	@Bean
	public RestTemplate restTemplate(){
		return new RestTemplate();
	}
}

Controller

@RestController
public class UserController {
    @Autowired
    RestTemplate restTemplate;
    @GetMapping("/buy")
    public String buyTicket(String name){
        String s = restTemplate.getForObject("http://PROVIDER-TICKET/ticket", String.class);
        return "购买力"+name+s;
    }
}

运行测试结果

  • 4.provider多实例测试

1.将不同端口号的provider-ticket打包放在service文件夹中

2.在两个终端窗口启动两个服务

Amy:~ Amy$ cd /Users/Amy/Downloads/service 
Amy:service Amy$ java -jar provider-ticket-0.0.1-8001SNAPSHOT.jar

Amy:~ Amy$ cd /Users/Amy/Downloads/service 
Amy:service Amy$ java -jar provider-ticket-0.0.1-8002SNAPSHOT.jar

3.启动ConsumerUserApplication

4.运行ConsumerUser的buy方法(多次运行),启用了负载均衡机制

地址:http://192.168.3.15:8200/buy?name=黄渤

猜你喜欢

转载自blog.csdn.net/qq_29479041/article/details/83549898