spring boot学习笔记(四):Spring Cloud

实例代码:http://git.oschina.net/null_584_3382/spring-cloud-examplegit

spring boot结合docker技术,能够构建微服务。特别是spring cloud的出现,为咱们解决了分布式开发经常使用遇到的问题。等配置管理,服务发现,断路器,代理服务,负载均衡等spring

1.Spring Cloud简介

1.1 配置服务

Spring Cloud提供了Config Server的解决方案,支持git和本地文件存放配置文件。使用@EnableConfigServer来启动配置服务docker

1.2 服务发现

Spring Cloud 经过Netfix OSS的Eureka来实现服务发现。Eureka Server提供服务注册bootstrap

其中服务端使用@EnableEurejaServer注解,客户端使用@EnbaleEurekaClientapi

1.3 路由网关

Spring经过Zuul开实现,支持自动路由到在Eureka上注册的俯卧,是同@EnbaleZuulProxy来启动路由代理app

1.4 负载均衡

Spring Cloud提供了Ribbon和Feign做为客户端的负载均衡。使用起来都很方便,负载均衡

1.5 断路器

断路器是为了解决某个方法调用失败的时候,调用后备方法来替代失败的方法。Spring Cloud使用@EnableCircuitBreaker来启动断路器支持。dom

2. Spring Cloud实例

parent pom文件分布式

<modules>
        <module>discovery</module>
        <module>config</module>
        <module>service</module>
        <module>gateway</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
    </parent>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

2.1 服务发现

依赖:ide

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

主要代码,就一个boot启动类,加上@EnableEurekaServer注解

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryApplication {
    public static void main(String[] args) {
        SpringApplication.run(DiscoveryApplication.class,args);
    }
}

配置文件:因为是单机环境,所以不须要注册本身(若是是集群服务就须要注册本身和集群其余发现服务)

eureka:
  client:
    register-with-eureka: false  
    fetch-registry: false

2.2 配置服务

依赖:

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

代码:@EnableConfigServer声明是一个配置管理服务,因为使用本地文件保存配置信息,须要在Erueka上注册,所以须要@EnableEurekaClient

@SpringBootApplication
@EnableConfigServer
@EnableEurekaClient
public class ConfigApplication {
   
    public static void main(String[] args) {
           SpringApplication.run(ConfigApplication.class, args);
       }
}

配置:

bootstrap.yml:

spring:
  application:
    name: config
  profiles:
    active: native #1
    
eureka:
  instance:
    non-secure-port: ${server.port:19882}
    metadata-map:
      instanceId: ${spring.application.name}:${random.value}   #2
  client:
    service-url:
      defaultZone: http://${eureka.host:localhost}:${eureka.port:19881}/eureka/  #3

#1 配置文件存在本地文件

#2 实例名字

#3 eureka地址

application.yml

spring:
  cloud:
    config:
      server:
        native:
          search-locations: classpath:/config #1

server:
  port: 19882

#1 配置文件存放的位置为 classpath:/config下

文件存储的规则为

  • /{application}/{profile}/{label}
  • /{application}-{profile}.yml  or properties
  • /{label}/{application}-{profile}.yml  or properties

computer.yml 表示 application的名字为computer 的服务(没有profile)

在computer.yml里面写入

my:
  name: lizo

2.3 服务模块

写一个简单的rest服务模块,

启动类:

@SpringBootApplication
@EnableEurekaClient
public class ComputerApplication {
   
      public static void main(String[] args) {
           SpringApplication.run(ComputerApplication.class, args);
       }
}

controller:提供一个加法运算和一个获取配置服务的rest api

@RestController
public class ComputerController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${my.name}")
    private String name;

    @RequestMapping("/add")
    public int add(@RequestParam("a") int a, @RequestParam("b") int b) {
        return a + b;
    }


    @RequestMapping("/name")
    public String name() {
        logger.info("########### call me!!!!!!");
        return name;
    }
}

bootstrap.yml

spring:
  application:
    name: computer
  cloud:
    config:
      enabled: true
      discovery:
        enabled: true
        service-id: CONFIG #1
eureka:
  instance:
    non-secure-port: ${server.port:19883}
  client:
    service-url:
      defaultZone: http://${eureka.host:localhost}:${eureka.port:19881}/eureka/

#1 从注册的服务中获取配置信息,配置服务注册的名字为CONFIG

2.4 网关

Controller:对外暴力的方法

@RestController
public class GatewayController {

    @Autowired
    ComputerFeignService computerFeignService;

    @RequestMapping("/getadd")
    public int getadd(@RequestParam("a") int a,@RequestParam("b") int b){
        return computerFeignService.add(a,b);
    }

    @RequestMapping("/getName")
    public String getName(){
        return computerFeignService.name();
    }
}

server:这里使用feign做为例子演示,

@FeignClient(value = "computer",fallback = ComputeClientHystrix.class)
public interface ComputerFeignService {
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    int add(@RequestParam("a") Integer a, @RequestParam("b") Integer b);

    @RequestMapping(value = "/name",method = RequestMethod.POST)
    String name();
}

value="computer"表示提供服务的application为computer,fallback是熔断器处理

@Component
public class ComputeClientHystrix implements ComputerFeignService{
    @Override
    public int add(@RequestParam("a") Integer a, @RequestParam("b") Integer b) {
        return -111919;
    }

    @Override
    public String name() {
        return "exception";
    }
}

bootstrap:仍是常规的 

spring:
  application:
    name: gateway

eureka:
  instance:
    non-secure-port: ${server.port:80}
  client:
    service-url:
      defaultZone: http://${eureka.host:localhost}:${eureka.port:19881}/eureka/

3 测试

依次启动发现服务和配置服务,其余的不分顺序

1. 服务发现

输入 http://localhost:19881/

发现其余服务都注册成功了

2.配置管理

输入 http://localhost/getName

输出 lizo 发现成功读取了配置文件中的内容

3.熔断

关掉computer服务 而后再访问http://localhost/getName

输出exception 说明熔断器是发挥了做用的

4. 负载均衡

若是启动2个computer服务,而后屡次调用http://localhost/getName,发现确实每次回调用其中一个,打日志"########### call me!!!!!!" 说明负载均衡也是作了的

 

实例代码:http://git.oschina.net/null_584_3382/spring-cloud-example

相关文章
相关标签/搜索