1.GovernanceService
GovernanceService用于与配置中心的交互
public interface GovernanceService {
void getConfig(String dataId, String uniqueName, String group, GovernanceListener listener, String errorMsg);
void getConfigSync(String dataId, String uniqueName, String group, GovernanceListener listener, String errorMsg);
String getConfig(String dataId, String uniqueName, String group, long timeoutMs, String errorMsg);
void unRegister(String dataId, String group);
}
2.Diamond服务器
默认实现为Diamond实现,所以在使用时,需要预先启动一个Diamond服务器端配置中心
参考阿里云文档:
https://help.aliyun.com/document_detail/44163.html
安装成功后,本地打开地址:http://jmenv.tbsite.net:8080/#/dsConfig
3.GovernanceListener监听配置文件变化
原生调用Diamond的addListener静态方法,也可以使用GovernanceListener接口,内部实现回调
public class GovernanceServiceTest {
@Test
public void test1() throws IOException {
GovernanceService service = HSFServiceContainer.getInstance(GovernanceService.class);
String val=service.getConfig("com.alibaba.edas.carshop.itemcenter.ItemService:1.0.0","","HSF",100,"");
Diamond.addListener("com.alibaba.edas.carshop.itemcenter.ItemService:1.0.0", "HSF", new ManagerListenerAdapter() {
public void receiveConfigInfo(String s) {
}
});
service.unRegister("com.seven:1.0.0","test");
service.getConfig("com.alibaba.edas.carshop.itemcenter.ItemService:1.0.0", "uniqueName", "HSF", new GovernanceListener() {
public void process(String s, String s1) {
}
},"errorMsg");
System.in.read();
}
}
当配置内容发生变更时,就会收到回调监听
4.使用场景
GovernanceService的使用非常广泛,可以用于动态配置变更的场景,
image.png如下示例
public class MachineRoomRuleComponent implements ServiceComponent, GovernanceListener {
private GovernanceService governanceService;
private Config config = ((ConfigService)HSFServiceContainer.getInstance(ConfigService.class)).getConfig();
public MachineRoomRuleComponent() {
this.governanceService = (GovernanceService)HSFServiceContainer.getInstance(GovernanceService.class, this.config.getString("hsf.governance.type"));
}
public void init(ServiceMetadata serviceMetadata) {
String dataId = serviceMetadata.getUniqueName() + ".RULES";
String group = serviceMetadata.getGroup();
String serviceUniqueName = serviceMetadata.getUniqueName();
if (this.governanceService != null) {
this.governanceService.getConfig(dataId, serviceUniqueName, group, this, "[MachineRoomRule Component] Failed to process rule");
}
}
public void process(String uniqueName, String configInfo) {
this.registerRule(uniqueName, configInfo);
}
网友评论