入门spring cloud

目录

spring cloud config 配置中心

 

服务注册中心eureka

目录结构

依赖maven包

application.yml

启动类

启动注册中心

注册服务提供者

目录结构

maven依赖

application.yml配置

启动类

提供的服务Controller

服务的发现与消费

目录结构

maven依赖包

application.yml

启动类

DiscoveryClient 发现服务

RestTemplate

feign

启动

Hystrix 断路器

zuul 网关


spring cloud config 配置中心

什么叫配置中心,就是管理和保存配置地方。说白了就是把配置文件放在一个地方进行管理。

  • 需要的maven依赖
<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
</dependency>
  • 目录结构

  • 启动类

@SpringBootApplication
@EnableConfigServer
public class TzwScloudconfigApplication {

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

}

利用注解 @EnableConfigServer,启动配置中心,使服务成为spring  cloud config服务

  • application.yml配置
server:
  port: 8888

spring:
  application:
    name: tzw-scloudconfig

  profiles:
    active: native

  cloud:
    config:
      server:
        native:
          search-locations: classpath:/config


  management:
    endpoints:
      web:
        exposure:
          include: refresh

server.port   设置端口

spring.application.name  设置服务名称

spring.profiles.active = native   这里利用了本地目录来储存配置数据。也可以用git,svn等来作为储存中心。

spring.cloud.config.server.native.search-locations=classpath:/config 

所以在config下建立配置文件 

  • management.endpoints.web.exposure.include = refresh 刷新配置

启动运行结果

 

 

 

服务注册中心eureka

  • 目录结构

  • 依赖maven包

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

当然有些地方也用 下面的包

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

有与spring cloud更新很快,所以1.5之前可以用spring-cloud-starter-eureka-server,但是2.0之后建议废弃。

建议使用spring-cloud-starter-netflix-eureka-server

 

  • application.yml

server:
  port: 8761 #设置端口

eureka:
  client:
    register-with-eureka: false  #是否注册eureka,由于该服务就是注册中心,所以不需要注册自己,设置为false
    fetch-registry: false  #是否获取注册的服务,由于该服务是注册中心,用来管理服务,不用检索服务,所以也设置为false
  • 启动类

package tzw.eureka.tzweurekaservice;

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

@SpringBootApplication
@EnableEurekaServer
public class TzwEurekaserviceApplication {

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

}
@SpringBootApplication  spring boot启动注解
@EnableEurekaServer  表示该服务是 eureka注册中心
  • 启动注册中心

启动服务,在浏览器中输入http://localhost:8761/

看到这个Instances currently registered with Eureka下是空的,表示还没有任何服务注册进来。

 

 

注册服务提供者

  • 目录结构

  • maven依赖

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

由于需要把该服务注册到eureka注册中心,所以它相当于eureka的服务端,需要spring-cloud-starter-netflix-eureka-client包。

  • application.yml配置

spring:
  application:
    name: tzw-eurekaprovider
eureka:
  instance:
    prefer-ip-address: true
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka
  • 启动类

package com.tzw.tzweurekaclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.tzw")
public class TzwEurekaclientApplication {

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

}

这里需要启动是扫面controller,所以需要加上@SpringBootApplication(scanBasePackages = "com.tzw")

  • 提供的服务Controller

package com.tzw.controller;

import org.springframework.http.RequestEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


@RestController
public class TzwController {

    @RequestMapping("/hello")
   public String  hello(Map map){

        System.out.println("123456");
       return  "123456";
   }
    @RequestMapping(value = "/hello_01",method = RequestMethod.POST)
   public String  hello_01(RequestEntity requestEntity){

        Object body = requestEntity.getBody();
        System.out.println(body.toString());

        System.out.println("------------------");
       return  body.toString();
   }


}

这样,我们的服务提供就写好了,接下里需要服务消费者了。

 

 

服务的发现与消费

  • 目录结构

 

  • maven依赖包

        <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>

这里需要说明一下,服务的发现提供三种方式,所以需要这两maven包,下面具体说明

  • application.yml

server:
  port: 8888
eureka:
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:8761/eureka  ## 注册到 eureka
  instance:
    preferIpAddress: true
spring:
  application:
    name: tzw-eurekadis
  • 启动类

package com.tzw.tzweurekadis;

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;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication(scanBasePackages = "com.tzw")
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.tzw")
@EnableCircuitBreaker
public class TzwEurekadisApplication {

    /**
     * 注入 RestTemplate
     * 并用 @LoadBalanced 注解,用负载均衡策略请求服务提供者
     * 这是 Spring Ribbon 的提供的能力
     * @return
     */
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

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

}

有四个主键,先不用关注@EnableCircuitBreaker这个注解。

@EnableDiscoveryClient 激活Eureka中DiscoveryClient的实现,表明可以来发现服务。

 主要提供了两种方式来发现服务,一个是DiscoveryClient,另一个是RestTemplate

  • DiscoveryClient 发现服务

    /**
         * 利用discoveryClient发现服务
     * @param serviceId
     * @return
     */
    @RequestMapping("/getHello_02/{serviceId}")
    public String findService_02(@PathVariable String serviceId){

        List<ServiceInstance> instances = discoveryClient.getInstances("tzw-eurekaprovider");
        String uri = instances.get(0).getUri().toString();
        String url = uri+"/{serviceId}";
        RestTemplate restTemplate = new RestTemplate();
        //exchange 方法
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("serviceId",serviceId);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, null, String.class, map);
        String body = exchange.getBody();

        return body;
    }
  • RestTemplate

相必大家也发现了启动类里的还有一些其他的类,就是下面这东西。就是声明了RestTemplate

 

    /**
     * 注入 RestTemplate
     * 并用 @LoadBalanced 注解,用负载均衡策略请求服务提供者
     * 这是 Spring Ribbon 的提供的能力
     * @return
     */
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
/**
     * 利用RestTemplate发现服务
     * @return
     */
    @RequestMapping("/getHello_03")
    public String findService_03(){

        String url = "http://tzw-eurekaprovider/hello_01";
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("serviceId","aaa");
        map.put("username","bbb");

        RequestEntity requestEntity = new RequestEntity(map,HttpMethod.POST,null);

        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, requestEntity
                , String.class, map);
        String body = exchange.getBody();

        return body;
    }

这里其实大家也发现了把,其实以上的两个方法其实是一个方式,最终都是通过RestTemplate实现的。

 

  • feign

@EnableFeignClients(basePackages = "com.tzw") 这个是通过feign来发现服务。

feign的实现,需要定义一个接口,利用@FeignClient的注解,来实现调用服务。

  /**
     * 利用feignClient方式发现服务
     * @return
     */
    @RequestMapping("/getHello_04")
    public String findService_04(){

        String hello = feignInter.getHello();

        return hello;


    }
package com.tzw.controller;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(name="tzw-eurekaprovider")
public interface FeignInter {

    @RequestMapping(method = RequestMethod.GET,value = "/hello")
    public String getHello();
}

所以目前提供三种方式。

  • 启动

这里我们启动eureka注册中心,启动服务提供者,启动服务消费者。

这里我们在浏览器中 调用消费者服务,消费者服务取注册中心寻找提供者服务,然后调用提供者服务中的方法。

浏览器中调用消费者

http://localhost:8888/getHello 

消费者然后会调用

http://tzw-eurekaprovider/hello 消费者服务 ,找到下面的方法,返回 123456

public String  hello(Map map){

     System.out.println("123456");
    return  "123456";
}

 

 

接下来我们会介绍短路器和网关。下期再见

Hystrix 断路器

 

zuul 网关

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值