zoukankan      html  css  js  c++  java
  • spring-cloud构架微服务(2)-全局配置二

      接上篇,实际项目中,可能会遇到有些配置项,例如:邮件地址、手机号等在服务已经上线之后做了改动(就当会出现这种情况好了)。然后你修改了配置信息,就得一个一个去重启对应的服务。spring-全局配置提供了一种热部署机制,可以在重启工程的前提下改变内存中配置项的值。

    还是中client-config项目,首先我们要再添加一个jar引用:

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

    这个监控包,包含了/refresh的api接口,接受post方法。

    上篇中的UserController类,我们只要在上面加入@RefreshScope这个注解,那么里面的 testProperty 这个属性值就会被动刷新。

    package com.bing.User;
    
    import com.bing.model.User;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.cloud.context.config.annotation.RefreshScope;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.Date;
    
    /**
     * Created by szt on 2016/11/18.
     */
    @RestController
    @RefreshScope
    public class UserController {
      @Value("${bing.for.test}")
      private String testProperty;
    
      @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
      public User getUser(@PathVariable("id") String id) {
        User user=new User();
        user.setName(testProperty);
        user.setId(id);
        user.setCreatedTime(new Date());
        return user;
      }
    }
    bingyulei007

    这个刷新需要手动请求。

    当我们启动配置服务器(上一篇中的configserver),然后启动client工程,访问路径http://localhost:8081/user/id1返回:

    {
      "id": "id1",
      "name": "hello-word",
      "createdTime": "2016-11-18 15:41:38"
    }
    bingyulei007

    我们更改配置文件中属性值

    bing.for.test=new-hello
    然后调用地址http://localhost:8081/refresh,之后这个节点上的属性值就会被刷新。验证效果,访问路径http://localhost:8081/user/id1返回:
    {
      "id": "id1",
      "name": "new-hello",
      "createdTime": "2016-11-18 16:03:22"
    }
    bingyulei007

    说明属性已经被刷新。但是实际随着项目的完善,我们后端可能会部署多个模块,每个模块也可能采用集群部署,我们不能傻傻的每个节点都去维护一个刷新。还好spring-cloud为我们提供了spring-bus模块,这个模块要依赖于服务发现机制,我们后面再说明。

  • 相关阅读:
    [LeetCode] Insertion Sort List
    [LeetCode] Sort List
    [国嵌攻略][162][USB协议分析]
    [国嵌攻略][161][USB总线介绍]
    [国嵌攻略][160][SPI驱动程序设计]
    [国嵌攻略][159][SPI子系统]
    [国嵌攻略][158][SPI裸机驱动设计]
    [国嵌攻略][157][SPI总线介绍]
    [国嵌攻略][156][I2C自编设备驱动设计]
    ueditor 单独图片上传 转载
  • 原文地址:https://www.cnblogs.com/shizhongtao/p/6078148.html
Copyright © 2011-2022 走看看