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模块,这个模块要依赖于服务发现机制,我们后面再说明。

 

posted @ 2016-11-18 16:18  bingyulei  阅读(836)  评论(0编辑  收藏  举报