分布式系统中,使用到nacos中的配置更新,怎么实现的呢;
其实就是客户端轮询服务端,检查配置,如果更新则修改当前配置;监测更新我们不说,这里提供下修改变量的方法~
1.我们先提供一个测试数据
@RestController
public class QiNiuController {
@Value("${ceshi}")
private String test;
2.编写获取spring中bean的方法
@Component
public class MyFactory implements ApplicationContextAware {
public static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
MyFactory.applicationContext = applicationContext;
}
}
3.修改变量方法(里面涉及获取代理类对象)
@GetMapping("edit")
public Object edit(String name) throws Exception {
QiNiuController bean = MyFactory.applicationContext.getBean(QiNiuController.class);
Object target = getTarget(bean);
Field test = target.getClass().getDeclaredField("test");
test.setAccessible(true);
test.set(target, name);
return name;
}
public static Object getTarget(Object proxy) throws Exception {
if (!AopUtils.isAopProxy(proxy)) {
return proxy;
}
if (AopUtils.isJdkDynamicProxy(proxy)) {
proxy = getJdkDynamicProxyTargetObject(proxy);
} else {
proxy = getCglibProxyTargetObject(proxy);
}
return getTarget(proxy);
}
private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
h.setAccessible(true);
Object dynamicAdvisedInterceptor = h.get(proxy);
Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
advised.setAccessible(true);
Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
return target;
}
private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
h.setAccessible(true);
AopProxy aopProxy = (AopProxy) h.get(proxy);
Field advised = aopProxy.getClass().getDeclaredField("advised");
advised.setAccessible(true);
Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
return target;
}
很简单,其实就是从spring中获取bean,并用反射方式修改变量值~