栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Cloud 入门 -- 搭建Eureka注册中心 实现服务者与消费者的服务调用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Cloud 入门 -- 搭建Eureka注册中心 实现服务者与消费者的服务调用



哈喽!大家好,我是【Bug 终结者】 ,【CSDN新星创作者】,阿里云技术博主,51CTO人气博主,INfoQ写作专家

一位上进心十足,拥有极强学习力的【Java领域博主】

【Bug 终结者】博客的领域是【面向后端技术】的学习,未来会持续更新更多的【后端技术】以及【学习心得】。 偶尔会分享些前端基础知识,会更新实战项目,面向企业级开发应用!
 如果有对【后端技术】、【前端领域】感兴趣的【小可爱】,欢迎关注【Bug 终结者】


❤️❤️❤️ 感谢各位大可爱小可爱! ❤️❤️❤️

文章目录

一、什么是Spring Cloud?二、Spring Cloud 与 Spring Boot 的关系三、Spring Cloud 与Dubbo 的区别

⛽服务的调用方式⛽社区更新力度 四、Spring Cloud 能干什么?五、什么是Eureka?六、Eureka 的特性及优点七、Spring Cloud入门案例 -- 搭建Eureka注册中心

✴️需求说明❇️ 效果图♻️项目结构⏳核心源码

⌚父级模块⌚实体类模块⌚注册中心模块⌚服务提供者模块⌚服务消费者模块 八、源码下载♨️往期精彩热文回顾⛵小结

一、什么是Spring Cloud?

摘自Spring Cloud官网

Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state). Coordination of distributed systems leads to boiler plate patterns, and using Spring Cloud developers can quickly stand up services and applications that implement those patterns. They will work well in any distributed environment, including the developer’s own laptop, bare metal data centres, and managed platforms such as Cloud Foundry.

以上翻译如下:

Spring Cloud 为开发者提供了工具来快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器、智能路由、微代理、控制总线、一次性令牌、全局锁、领导选举、分布式会话,集群状态)。分布式系统的协调导致了样板模式,使用 Spring Cloud 开发人员可以快速建立实现这些模式的服务和应用程序。它们在任何分布式环境中都能很好地工作,包括开发人员自己的笔记本电脑、裸机数据中心以及 Cloud Foundry 等托管平台。

大致意思就是 Spring Cloud 是一个分布式框架,基于Spring Boot微服务,将一个一个独立的模块聚合,达到了“高内聚 · 低耦合 ”

二、Spring Cloud 与 Spring Boot 的关系

Spring Boot专注于开发方便的开发单个个体微服务;Spring Cloud是关注全局的微服务协调整理治理框架,它将Spring Boot开发的一个个单体微服务,整合并管理起来,为各个微服务之间提供:配置管理、服务发现、断路器、路由、为代理、事件总栈、全局锁、决策竞选、分布式会话等等集成服务;Spring Boot专注于快速、方便的开发单个个体微服务,Spring Cloud关注全局的服务治理框架Spring Boot 可以离开Spring Cloud 独立运行,而Spring Cloud 不可以离开Spring Boot,是基于Spring Boot的 三、Spring Cloud 与Dubbo 的区别 ⛽服务的调用方式

Spring Cloud采用HTTP的REST方式调用服务,Dubbo采用RPC框架实现远程调用服务

⛽社区更新力度

Dubbo活跃度较低

Spring Cloud社区活跃度比较高

定位不同:Dubbo 的定位是一款高性能RPC框架,而Spring Cloud的目标是分布式微服务架构的一站式解决方案

框架Spring CloudDubbo
服务注册中心Spring Cloud Netfix EurekaZookkeper
服务调用方式REST APIRPC
服务监控Spring Boot AdminDubbo-monitor
断路器Spring Cloud Netfix Hystrix未完善,引用外部断路器
服务网关Spring Cloud Netfix Zuul
分布式配置Spring Cloud Config
服务跟踪Spring Cloud Sleuth
消息总栈Spring Cloud Bus
数据流Spring Cloud Strem
批量任务Spring Cloud Task

两者最大的区别:Spring Cloud 抛弃了 Dubbo 的 RPC,采用了基于 HTTP 的 REST方式

严格来说,这两种方式各有优劣。虽然从一定程度上来说,后者牺牲了服务调用的性能,但也避免了上面提到的原生RPC带来的问题。而且REST相比RPC更为灵活,服务提供方和调用方的依赖只依靠一纸契约,不存在代码级别的强依赖,这个优点在当下强调快速演化的微服务环境下,显得更加合适。

四、Spring Cloud 能干什么?

Distributed/versioned configuration 分布式/版本控制配置Service registration and discovery 服务注册与发现Routing 路由Service-to-service calls 服务到服务的调用Load balancing 负载均衡配置Circuit Breakers 断路器Distributed messaging 分布式消息管理 五、什么是Eureka?

Netflix在涉及Eureka时,遵循的就是API原则.

Eureka是Netflix的子模块,也是核心模块之一。Eureka是基于REST的服务,用于定位服务,以实现云端中间件层服务发现和故障转移,服务注册与发现对于微服务来说是非常重要的,有了服务注册与发现,只需要使用服务的标识符,就可以访问到服务,而不需要修改服务调用的配置文件了,功能类似于Dubbo的注册中心,比如Zookeeper。

六、Eureka 的特性及优点

Eureka是一个基于REST的服务,用于定位服务,以实现云端中间层服务发现和故障转移。Eureka 主管服务注册与发现,在微服务中,以后了这两者,只需要使用服务的标识符,就是那个在每个服务的yml文件中取得服务名称, 就可以访问到服务,不需要修改服务调用的配置文件。Eureka遵循AP原则 高可用,分区容错性,因为使用了自我保护机制所以保证了高可用。

Eureka两大组件:Eureka Server(提供注册服务)、 Eureka Client(JAVA客户端,负责发送心跳)

Eureka三大角色:

Eureka Server:提供服务注册和发现Service Provider:服务提供方,将自身服务注册到Eureka,从而使服务消费方能够找到Service Consumer:服务消费方,从Eureka获取注册服务列表,从而能够消费服务。 七、Spring Cloud入门案例 – 搭建Eureka注册中心 ✴️需求说明

基于Spring Boot聚合工程

使用Spring Cloud 实现分布式应用

服务提供者,将服务注册到Eureka注册中心服务消费者,从Eureka取出调用的服务并获取返回结果

流程图

❇️ 效果图

♻️项目结构

模块说明

spring_cloud模块:父级模块springcloud-api:实体类模块springcloud-eureka:注册中心模块springcloud-provider:服务提供者模块springcloud-consumer:服务消费者模块 ⏳核心源码 ⌚父级模块

pom.xml



    4.0.0

    org.example
    spring_cloud
    1.0-SNAPSHOT
    
        springcloud-api
        springcloud-provider
        springcloud-eureka
        springcloud-consumer
    


    
    pom

    
        UTF-8
        1.8
        1.8
        4.12
        1.2.17
        1.16.18
    

    
        
            
                org.springframework.cloud
                spring-cloud-alibaba-dependencies
                0.2.0.RELEASE
                pom
                import
            
            
            
                org.springframework.cloud
                spring-cloud-dependencies
                Greenwich.SR1
                pom
                import
            
            
            
                org.springframework.boot
                spring-boot-dependencies
                2.1.4.RELEASE
                pom
                import
            
            
            
                mysql
                mysql-connector-java
                5.1.47
            
            
                com.alibaba
                druid
                1.1.10
            
            
            
                org.mybatis.spring.boot
                mybatis-spring-boot-starter
                1.3.2
            
            
            
                ch.qos.logback
                logback-core
                1.2.3
            
            
                junit
                junit
                ${junit.version}
            
            
                log4j
                log4j
                ${log4j.version}
            
            
                org.projectlombok
                lombok
                ${lombok.version}
            
        
    


⌚实体类模块

pom.xml



    
        spring_cloud
        org.example
        1.0-SNAPSHOT
    
    4.0.0

    springcloud-api

    
        8
        8
    

    
        
            org.projectlombok
            lombok
        
    


Dept实体类

package com.wanshi.springcloud.entity;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@NoArgsConstructor
//支持链式编程
@Accessors(chain = true)
public class Dept {

    private Integer dept_noid;

    private String dept_name;

    private String db_source;
}

⌚注册中心模块

pom.xml



    
        spring_cloud
        org.example
        1.0-SNAPSHOT
    
    4.0.0

    springcloud-eureka

    
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka-server
            1.4.6.RELEASE
        
        
        
            org.springframework.boot
            spring-boot-devtools
        
    


application.yml

server:
  port: 7001

# eureka 配置
eureka:
  instance:
    hostname: localhost # eureka 服务端的实例名称
  client:
    register-with-eureka: false # 是否向 eureka 注册自己,不注册自己
    fetch-registry: false # fetch-registry 如果为false,表示自己为注册中心
    service-url: # 将默认的url去掉,替换为自己的,监控页面
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

启动类

package com.wanshi.springcloud;

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

@SpringBootApplication
// EnableEurekaServer 启动Eureka服务
@EnableEurekaServer
public class EurekaServerMainApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerMainApplication.class, args);
    }
}

⌚服务提供者模块

pom.xml



        
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
            1.4.6.RELEASE
        

        
        
            org.springframework.boot
            spring-boot-starter-actuator
        


        
        
            org.example
            springcloud-api
            1.0-SNAPSHOT
        
        
        
            junit
            junit
            test
        

        
        
            mysql
            mysql-connector-java
        

        
            com.alibaba
            druid
        

        
            ch.qos.logback
            logback-core
        

        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
        

        
        
            org.springframework.boot
            spring-boot-test
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.boot
            spring-boot-starter-jetty
        

        
        
            org.springframework.boot
            spring-boot-devtools
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        

    

application.yml

server:
  port: 8001
  servlet:
    context-path: /springcloud-provider-dept/

spring:
  application:
    name: SpringCloudProviderDept
  datasource:
    url: jdbc:mysql://localhost:3306/db_spring_cloud01
    username: root
    password: 111111
    driver-class-name: com.mysql.jdbc.Driver


# Eureka的配置,服务注册到那里
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/
  instance:
    instance-id: springcloud-provider-dept8001 # 修改 Eureka上的默认描述信息

info:
  app.name: wanshi-springcloud
  company.name: blog.wanshi.com

DeptController

package com.wanshi.springcloud.controller;

import com.wanshi.springcloud.entity.Dept;
import com.wanshi.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept/")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @GetMapping("list")
    public List list() {
        return deptService.list();
    }

    @PostMapping("insert")
    public Integer insert(@RequestBody Dept param) {
        return deptService.insert(param);
    }

    @PostMapping("get/{id}")
    public Dept get(@PathVariable("id") Integer id) {
        Dept param = new Dept();
        param.setDept_noid(id);
       return deptService.get(param);
    }

}

⌚服务消费者模块

pom.xml

 

        
        
            org.springframework.cloud
            spring-cloud-starter-ribbon
            1.4.6.RELEASE
        

        
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
            1.4.6.RELEASE
        

        
            org.example
            springcloud-api
            1.0-SNAPSHOT
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.springframework.boot
            spring-boot-devtools
        

    

application.yml

server:
  port: 80

# Eureka配置
eureka:
  client:
    register-with-eureka: false # 不向注册中心注册自己
    service-url:
      defaultZone: http://localhost:7001/eureka/

ConfigBean配置

package com.wanshi.springcloud.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ConfigBean {

    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

DeptConsumerController

package com.wanshi.springcloud.controller;

import com.wanshi.springcloud.entity.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/consumer/dept/")
public class DeptConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    private static final String REST_URL_PREFIX = "http://localhost:8001/springcloud-provider-dept";

    @GetMapping("get/{id}")
    public Integer get(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Integer.class);
    }

    @GetMapping("list")
    public List list() {
        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class);
    }

    @PostMapping("insert")
    public Integer insert(@RequestBody Dept param) {
        return restTemplate.patchForObject(REST_URL_PREFIX + "/dept/insert", param, Integer.class);
    }
}

启动类

package com.wanshi.springcloud;

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

// Ribbon 和 Eureka 整合以后,客户端可以直接调用,不用关心IP地址和端口号
@SpringBootApplication
@EnableEurekaClient
public class DeptConsumerApplication {

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

八、源码下载

Spring Cluod搭建Eureka注册中心实现服务者与消费者的服务调用

♨️往期精彩热文回顾

✈️ Netty进阶 – WebSocket长连接开发

✈️ Netty进阶 – 非阻塞网络编程 实现群聊+私聊+心跳检测系统

✈️ Postman测试工具调试接口详细教程【向后端发送Json数据并接收返回的Json结果】

✈️ Java面向对象 — 吃货联盟订餐系统(完整版)

✈️ 一分钟教你快速 搭建Vue脚手架(Vue-Cli)项目并整合ElementUI

⛵小结

以上就是【Bug 终结者】对Spring Cloud 搭建Eureka注册中心 实现服务者与消费者的服务调用 简单的概述,理解代码不难,多多练习,该工程是一个分布式应用框架,注册了Eureka注册中心作为服务的中转站,可以多多练习去巩固自己的技术~

如果这篇【文章】有帮助到你,希望可以给【Bug 终结者】点个赞,创作不易,如果有对【后端技术】、【前端领域】感兴趣的小可爱,也欢迎关注❤️❤️❤️ 【Bug 终结者】❤️❤️❤️,我将会给你带来巨大的【收获与惊喜】!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/780715.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号