Spring Cloud---第一天

目录

初识 Spring Cloud

微服务架构

走进 Spring Cloud

Spring Cloud 与 Dubbo 对比

总结

Spring Cloud 服务治理

Eureka

实验一

Eureka – 相关配置及特性

Eureka –高可用

实验二

Consul

实验三

Nacos

实验四

Ribbon 客户端负载均衡

Ribbon 概述

Ribbon 简化远程调用

Ribbon 负载均衡

Ribbon 负责均衡策略

设置负载均衡策略

 实验五


初识 Spring Cloud

微服务架构

架构演进:

定义与特点:

  • "微服务”,一词源于 Martin Fowler的名为 Microservices 的博文,可以在他的官方博客上找到http://martinfowler.com/articles/microservices.html
  • 微服务是系统架构上的一种设计风格,它的主旨是将一个原本独立的系统拆分成多个小型服务,这些小型服务都在各自独立的进程中运行,服务之间一般通过 HTTP 的 RESTfuL API 进行通信协作。
  • 被拆分成的每一个小型服务都围绕着系统中的某一项或些耦合度较高的业务功能进行构建,并且每个服务都维护着白身的数据存储、业务开发自动化测试案例以及独立部署机制。
  • 由于有了轻量级的通信协作基础,所以这些微服务可以使用不同的语言来编写。

走进 Spring Cloud

定义和特点:

  • Spring Cloud 是一系列框架的有序集合。
  • Spring Cloud 并没有重复制造轮子,它只是将目前各家公司开发的比较成熟、经得起实际考验的服务框架组合起来。
  • 再通过 Spring Boot 风格进行封装屏蔽掉了复杂的配置和实现原理,最终给开发者留出了一套简单易懂、易部署和易维护的分布式系统开发工具包。
  • 它利用Spring Boot的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注册、配置中心、消息总线、负载均衡、 断路器、数据监控等,都可以用Spring Boot的开发风格做到一键启动和部署。
  • Spring Cloud项目官方网址:https://spring.io/projects/spring-cloud  

Spring Cloud 版本命名方式:

  • Spring Cloud 版本命名方式,采用了伦敦地铁站的名称,同时根据字母表的顺序来对应版本时间顺序,比如:最早的Release版本:Angel,第二个Release版本:Brixton,然后是Camden、Dalston、Edgware,Finchley,Greenwich,Hoxton。
  • 目前最新的是Hoxton版本。

Spring Cloud 与 Dubbo 对比

  • Spring Cloud  与 Dubbo 都是实现微服务有效的工具。
  • Dubbo 只是实现了服务治理,而 Spring Cloud 子项目分别覆盖了微服务架构下的众多部件。
  • Dubbo 使用 RPC 通讯协议,Spring Cloud 使用 RESTful 完成通信,Dubbo 效率略高于 Spring Cloud。

总结

  • 微服务就是将项目的各个模块拆分为可独立运行、部署、测试的架构设计风格。
  • Spring 公司将其他公司中微服务架构常用的组件整合起来,并使用 SpringBoot 简化其开发、配置。称为 Spring Cloud ,Spring Cloud  与 Dubbo都是实现微服务有效的工具。
  • Dubbo 性能更好,而 Spring Cloud 功能更全面。

Spring Cloud 服务治理

Eureka

介绍

  • Eureka 是 Netflix 公司开源的一个服务注册与发现的组件 。
  • Eureka 和其他 Netflix 公司的服务组件(例如负载均衡、熔断器、网关等) 一起,被 Spring Cloud 社区整合为Spring-Cloud-Netflix 模块。
  • Eureka 包含两个组件:Eureka Server (注册中心) 和 Eureka Client (服务提供者、服务消费者)。

使用过程

  1. 搭建 Provider  和 Consumer 服务。
  2. 使用 RestTemplate (模板)完成远程调用。
  3. 搭建 Eureka Server 服务。
  4. 改造 Provider  和 Consumer 称为 Eureka Client。
  5. Consumer 服务 通过从 Eureka Server 中抓取 Provider 地址 完成 远程调用

RestTemplate (模板)

  • Spring提供的一种简单便捷的模板类,用于在 java 代码里访问 restful 服务。
  • 其功能与 HttpClient 类似,但是 RestTemplate 实现更优雅,使用更方便。

搭建 Eureka Server 服务

  1. 创建 eureka-server 模块
  2. 引入 SpringCloud 和 euraka-server 相关依赖
  3. 完成 Eureka Server 相关配置
  4. 启动该模块

改造 Provider  和 Consumer 称为 Eureka Client

  1. 引 eureka-client 相关依赖
  2. 完成 eureka client 相关配置
  3. 启动 测试

实验一

项目结构:

先建立java空项目,名字为cloud,之后建立maven模块,名字为spring-cloud-parent,作为父模块,其有两个子maven模块,为eureku-provider和eureku-consumer。

1.spring-cloud-parent 中pom.xml 引入依赖

 <!--spring boot 环境 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/>
    </parent>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>11</java.version>
        <!--spring cloud 版本-->
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
    </properties>

    <!--引入Spring Cloud 依赖-->
    <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.eureka-server模块

2.1模块结构和pom.xml引入依赖

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

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

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>
    </dependencies>

2.2 application.yml 内容

server:
  port: 8761

# eureka 配置
# eureka 一共有4部分 配置
# 1. dashboard:eureka的web控制台配置
# 2. server:eureka的服务端配置
# 3. client:eureka的客户端配置
# 4. instance:eureka的实例配置


eureka:
  instance:
    hostname: localhost # 主机名
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka # eureka服务端地址,将来客户端使用该地址和eureka进行通信

    register-with-eureka: false # 是否将自己的路径 注册到eureka上。eureka server 不需要的,eureka provider client 需要
    fetch-registry: false # 是否需要从eureka中抓取路径。eureka server 不需要的,eureka consumer client 需要

 2.3 EurekaApp 类    添加@EnableEurekaServer

@SpringBootApplication
// 启用EurekaServer
@EnableEurekaServer
public class EurekaApp {

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

    }
}

运行类,在浏览器输入:http://localhost:8761/   就可以打开Spring Eureka 界面了!

3.eureka-provider模块

3.1 模块结构、pom.xml引入依赖和ProviderApp启动类


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

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

    </dependencies>
/**
 * 启动类
 */

@EnableEurekaClient //该注解 在新版本中可以省略
@SpringBootApplication
public class ProviderApp {


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

 3.2 application.yml

server:
  port: 8001


eureka:
  instance:
    hostname: localhost # 主机名
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka # eureka服务端地址,将来客户端使用该地址和eureka进行通信
spring:
  application:
    name: eureka-provider # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径

3.3 provider.domain.Goods 类

/**
 * 商品实体类
 */
public class Goods {

    private int id;
    private String title;//商品标题
    private double price;//商品价格
    private int count;//商品库存

    public Goods() {
    }

    public Goods(int id, String title, double price, int count) {
        this.id = id;
        this.title = title;
        this.price = price;
        this.count = count;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

3.4 provider.controller.GoodsController 类

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @GetMapping("/findOne/{id}")
    public Goods findOne(@PathVariable("id") int id){

        Goods goods = goodsService.findOne(id);

        return goods;
    }
}

3.5 provider.service.GoodsService.java 类

/**
 * Goods 业务层
 */
@Service
public class GoodsService {

    @Autowired
    private GoodsDao goodsDao;


    /**
     * 根据id查询
     * @param id
     * @return
     */
    public Goods findOne(int id){
        return goodsDao.findOne(id);
    }
}

3.6 provider.dao.GoodsDao.java 类

/**
 * 商品Dao
 */

@Repository
public class GoodsDao {


    public Goods findOne(int id){
        return new Goods(id,"华为手机",3999,10000);
    }
}

4.eureka-consumer 模块

4.1模块结构、pom文件和启动类ConsumerApp

 <dependencies>

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


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

    </dependencies>
@EnableDiscoveryClient // 激活DiscoveryClient
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApp {


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

4.2 consumer.domain.Goods类   同上

4.3 controller.OrderController类

/**
 * 服务的调用方
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){
        System.out.println("findGoodsById..."+id);


        /*
            //远程调用Goods服务中的findOne接口
            使用RestTemplate
            1. 定义Bean  restTemplate
            2. 注入Bean
            3. 调用方法
         */

        /*
            动态从Eureka Server 中获取 provider 的 ip 和端口
             1. 注入 DiscoveryClient 对象.激活
             2. 调用方法


         */

        //演示discoveryClient 使用
        List<ServiceInstance> instances = discoveryClient.getInstances("EUREKA-PROVIDER");

        //判断集合是否有数据
        if(instances == null || instances.size() == 0){
            //集合没有数据
            return null;
        }

        ServiceInstance instance = instances.get(0);
        String host = instance.getHost();//获取ip
        int port = instance.getPort();//获取端口

        System.out.println(host);
        System.out.println(port);

        String url = "http://"+host+":"+port+"/goods/findOne/"+id;
        // 3. 调用方法
        Goods goods = restTemplate.getForObject(url, Goods.class);


        return goods;
    }
}

4.4 consumer.config.RestTemplateConfig类

@Configuration
public class RestTemplateConfig {


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

运行结果:

Eureka – 相关配置及特性

eureka 一共有4部分 配置

  1. server : eureka 的服务端配置
  2. client : eureka 的客户端配置
  3. instance : eureka 的实例配置
  4. dashboard : eureka 的web控制台配置

client : eureka 的客户端配置

参数:

改变参数之前的:

 改变 eureka-provider模块的application.yml文件

server:
  port: 8002


eureka:
  instance:
    hostname: localhost # 主机名
    prefer-ip-address: true # 是否将自己的ip注册到eureka中,默认false 注册 主机名
    ip-address: 127.0.0.1 # 设置当前实例ip
    instance-id: ${eureka.instance.ip-address}:${spring.application.name}:${server.port}           # 修改instance-id显示
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka # eureka服务端地址,将来客户端使用该地址和eureka进行通信
spring:
  application:
    name: eureka-provider # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径

显示

server : eureka 的服务端配置

在eureka-server模块 application.yml配置

Eureka –高可用

 左边这个模式,Eureka Server挂了,那么整个系统就挂了。右边有多个Eureka Server,它们之间相互注册,一个Eureka Server挂了,不影响整个系统的正常运行。可以称Eureka Server集群

过程

  1. 准备两个Eureka Server
  2. 分别进行配置,相互注册
  3. Eureka Client 分别注册到这两个 Eureka Server中

实验二

项目结构

新建立eureka-server-1和eureka-server-2模块,两者的application.yml文件分别为

server:
  port: 8761


eureka:
  instance:
    hostname: eureka-server1 # 主机名
  client:
    service-url:
      defaultZone: http://eureka-server2:8762/eureka

    register-with-eureka: true # 是否将自己的路径 注册到eureka上。eureka server 不需要的,eureka provider client 需要
    fetch-registry: true # 是否需要从eureka中抓取路径。eureka server 不需要的,eureka consumer client 需要

spring:
  application:
    name: eureka-server-ha
server:
  port: 8762


eureka:
  instance:
    hostname: eureka-server2 # 主机名
  client:
    service-url:
      defaultZone: http://eureka-server1:8761/eureka

    register-with-eureka: true # 是否将自己的路径 注册到eureka上。eureka server 不需要的,eureka provider client 需要
    fetch-registry: true # 是否需要从eureka中抓取路径。eureka server 不需要的,eureka consumer client 需要

spring:
  application:
    name: eureka-server-ha  # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径

在电脑上配置hosts文件

127.0.0.1   eureka-server1

127.0.0.1   eureka-server2

 更改 eureka-provider模块和eureka-consumer模块 application.yml

eureka:
  client:
    service-url:
      defaultZone: http://eureka-server1:8761/eureka,http://eureka-server2:8762/eureka # 

运行结果:

Consul

介绍

  • Consul 是由 HashiCorp 基于 Go 语言开发的,支持多数据中心,分布式高可用的服务发布和注册服务软件。
  • 用于实现分布式系统的服务发现与配置。
  • 使用起来也较 为简单。具有天然可移植性(支持Linux、windows和Mac OS X);安装包仅包含一个可执行文件,方便部署 。
  • 官网地址: https://www.consul.io

使用

在含有consul.exe文件夹下,打开shell命令窗口,输入命令: .\consul  agent   -dev

之后在浏览器输入地址,就可以打开了:http://localhost:8500/

快速入门

  1. 搭建 Provider  和 Consumer 服务。
  2. 使用 RestTemplate 完成远程调用。
  3. 将Provider服务注册到Consul中。
  4. Consumer 服务 通过从 Consul 中抓取 Provider 地址 完成 远程调用

实验三

项目结构

consul-provider模块

1.pom文件引入相关依赖

<dependencies>

        <!--consul 客户端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>

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

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

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

    </dependencies>

2.application.yml 文件

server:
  port: 8000
spring:
  cloud:
    consul:
      host: localhost # consul 服务端的 ip
      port: 8500 # consul 服务端的端口 默认8500
      discovery:
        service-name: ${spring.application.name} # 当前应用注册到consul的名称
        prefer-ip-address: true # 注册ip

  application:
    name: consul-provider # 应用名称

3.GoodsController 类、GoodsService类、GoodsDao类和Goods类

实验 一  eureka-provider模块 一样

4.启动类ConsulProviderApp

@SpringBootApplication
public class ConsulProviderApp {

    public static void main(String[] args) {

        SpringApplication.run(ConsulProviderApp.class,args);
    }
}

consul-consumer 模块

1.pom文件引入相关依赖

同上

2.application.yml 文件

server:
  port: 9001


spring:
  cloud:
    consul:
      host: localhost # consul 服务端的 ip
      port: 8500 # consul 服务端的端口 默认8500
      discovery:
        service-name: ${spring.application.name} # 当前应用注册到consul的名称
        prefer-ip-address: true # 注册ip

  application:
    name: consul-consumer # 应用名称

2.RestTemplateConfig 类

@Configuration
public class RestTemplateConfig {


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

3.OrderController 类

**
 * 服务的调用方
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){
        //演示discoveryClient 使用
        List<ServiceInstance> instances = discoveryClient.getInstances("consul-PROVIDER");

        //判断集合是否有数据
        if(instances == null || instances.size() == 0){
            //集合没有数据
            return null;
        }

        ServiceInstance instance = instances.get(0);
        String host = instance.getHost();//获取ip
        int port = instance.getPort();//获取端口

        System.out.println(host);
        System.out.println(port);

        String url = "http://"+host+":"+port+"/goods/findOne/"+id;
        // 3. 调用方法
        Goods goods = restTemplate.getForObject(url, Goods.class);


        return goods;
    }
}

4.Goods类和启动类ConsulConsumerApp

Goods类同上

@SpringBootApplication
public class ConsulConsumerApp {

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

最后:先打开consul.exe软件,浏览器上测试运行

Nacos

介绍

  • Nacos(Dynamic Naming and Configuration Service) 是阿里巴巴2018年7月开源的项目。
  • 它专注于服务发现和配置管理领域 致力于帮助您发现、配置和管理微服务。
  • Nacos 支持几乎所有主流类型的“服务”的发现、配置和管理。
  • 一句话概括就是Nacos = Spring Cloud注册中心 + Spring Cloud配置中心。
  • 官网:https://nacos.io/   下载地址:https://github.com/alibaba/nacos/releases

使用

解压下载的文件,启动startup.cmd。startup.sh是Linux下的启动方式。

 启动后,再浏览器输入,就可以启动了:http://localhost:8848/nacos 

登录名/密码:nacos

实验四

项目结构

工程pom.xml文件和实验一 一样

nacos-provider模块

1.pom.xml 引入nacos相关依赖

<dependencies>
        <!--nacos-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>0.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

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

2.application.yml文件

erver:
  port: 8000



spring:
  cloud:
    nacos:
      discovery:
        server-addr:  127.0.0.1:8848 # 配置nacos 服务端地址
  application:
    name: nacos-provider # 服务名称

3.GoodsController 类、GoodsService类、GoodsDao类和Goods类

实验 一  eureka-provider模块 一样

4.启动类NacosProviderApp

@SpringBootApplication
public class NacosProviderApp {

    public static void main(String[] args) {

        SpringApplication.run(NacosProviderApp.class,args);
    }
}

nacos-consumer模块

1.pom.xml 引入nacos相关依赖

同上

2.application.yml文件

server:
  port: 9001


spring:
  cloud:
    nacos:
      discovery:
        server-addr:  127.0.0.1:8848 # 配置nacos 服务端地址
  application:
    name: nacos-consumer # 服务名称

3.RestTemplateConfig类和OrderController类

实验三 一样

最后:运行软件,在浏览器上运行测试

Ribbon 客户端负载均衡

Ribbon 概述

  • Ribbon是 Netflix 提供的一个基于HTTP和TCP的客户端负载均衡工具。
  • Ribbon主要有两个功能: 1、简化远程调用     2、负载均衡

  •  服务端负载均衡  
  1. 负载均衡算法在服务端
  2. 由负载均衡器维护服务地址列表
  • 客户端负载均衡
  1. 负载均衡算法在客户端
  2. 客户端维护服务地址列表

Ribbon 简化远程调用

Ribbon 可以与 简化 RestTemplate 的远程调用

Ribbon 负载均衡

Ribbon 负责均衡策略

  • 随机 :RandomRule
  • 轮询 :RoundRobinRule
  • 最小并发:BestAvailableRule
  • 过滤:AvailabilityFilteringRule
  • 响应时间:WeightedResponseTimeRule
  • 轮询重试:RetryRule
  • 性能可用性:ZoneAvoidanceRule

设置负载均衡策略

 实验五

项目结构

 工程pom.xml项目依赖和实验一样

eureka-consumer-1模块

1.pom.xml依赖

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

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

2.application.yml 文件   设置Ribbon的负载均衡策略

server:
  port: 9001


eureka:
  instance:
    hostname: localhost # 主机名
  client:
    service-url:
      #defaultZone:  http://eureka-server1:8761/eureka,http://eureka-server2:8762/eureka  # eureka服务端地址,将来客户端使用该地址和eureka进行通信
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: eureka-consumer # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径


# 配置的方式设置Ribbon的负载均衡策略
EUREKA-PROVIDER: # 设置的服务提供方的 应用名称
  ribbon:
    NFloadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 策略类

3.OrderController类和RestTemplateConfig类

@Configuration
public class RestTemplateConfig {


    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
/**
 * 服务的调用方
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 使用 Ribbon 简化restTemplate调用
     * 1. 在声明restTemplate的Bean时候,添加一个注解:@LoadBalanced
     * 2. 在使用restTemplate发起请求时,需要定义url时,host:port可以替换为 服务提供方的 应用名称
     * @param id
     * @return
     */

    @GetMapping("/goods2/{id}")
    public Goods findGoodsById2(@PathVariable("id") int id){


        String url = "http://EUREKA-PROVIDER/goods/findOne/"+id;
        // 3. 调用方法
        Goods goods = restTemplate.getForObject(url, Goods.class);

        return goods;
    }
}

4.Goods类和启动类ConsulConsumerApp

Goods类同上

@SpringBootApplication
public class ConsulConsumerApp {

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

eureka-provider-1模块

1.pom.xml文件依赖

同eureka-consumer-1模块

2.application.yml文件

server:
  port: 8002

eureka:
  instance:
    hostname: localhost # 主机名
    prefer-ip-address: true # 将当前实例的ip注册到eureka server 中。默认是false 注册主机名
    ip-address: 127.0.0.1 # 设置当前实例的ip
    instance-id: ${eureka.instance.ip-address}:${spring.application.name}:${server.port} # 设置web控制台显示的 实例id
    lease-renewal-interval-in-seconds: 3 # 每隔3 秒发一次心跳包
    lease-expiration-duration-in-seconds: 9 # 如果9秒没有发心跳包,服务器呀,你把我干掉吧~
  client:
    service-url:
      #defaultZone: http://eureka-server1:8761/eureka,http://eureka-server2:8762/eureka # eureka服务端地址,将来客户端使用该地址和eureka进行通信
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: eureka-provider # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径

3.GoodsController 类、GoodsService类、GoodsDao类和Goods类

实验 一  eureka-provider模块 一样

4.启动类ProviderApp

@EnableEurekaClient //该注解 在新版本中可以省略
@SpringBootApplication
public class ProviderApp {


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

eureka-server-01模块

1.pom.xm文件引入相关依赖

 <dependencies>

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

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

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>

    </dependencies>

2.application.yml文件

server:
  port: 8761

# eureka 配置
# eureka 一共有4部分 配置
# 1. dashboard:eureka的web控制台配置
# 2. server:eureka的服务端配置
# 3. client:eureka的客户端配置
# 4. instance:eureka的实例配置

eureka:
  instance:
    hostname: localhost # 主机名
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka # eureka服务端地址,将来客户端使用该地址和eureka进行通信
    register-with-eureka: false # 是否将自己的路径 注册到eureka上。eureka server 不需要的,eureka provider client 需要
    fetch-registry: false # 是否需要从eureka中抓取路径。eureka server 不需要的,eureka consumer client 需要
  server:
    enable-self-preservation: false # 关闭自我保护机制
    eviction-interval-timer-in-ms: 3000 # 检查服务的时间间隔

3.启动类EurekaApp

@SpringBootApplication
// 启用EurekaServer
@EnableEurekaServer
public class EurekaApp {

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

    }
}

最后:打开浏览器测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值