由于今年接到一个大的项目,食品安全全链路追溯项目,流程就很少发博客了,但是我还一直坚持到一线,不停的完善流程的项目。
在很多场景中,我们都需要在监听器中去动态调用业务接口,如果企业内部使用的微服务,nacos,我们又当怎么去动态调用接口呢
通过配置就能很好的调用Nacos的接口
目标:只需要配置,不需要硬编码来调用接口
- 动态配置调用
@Component
public class DynamicFeignClientFactory<T> {
private FeignClientBuilder feignClientBuilder;
public DynamicFeignClientFactory(ApplicationContext appContext) {
this.feignClientBuilder = new FeignClientBuilder(appContext);
}
public T getFeignClient(final Class<T> type, String serviceId,String path) {
return this.feignClientBuilder.forType(type, serviceId).path(path).build();
}
}
public interface SpringCloudDynamicApi {
@PostMapping(value = "", produces = "application/json")
JSONObject postExecute(@RequestBody Map<String,String> params);
@GetMapping(value = "", produces = "application/json")
JSONObject getExecute(@RequestBody Map<String,String> params);
}
@FeignClient(name = "dynamicClient",contextId = "dynamicClient")
public interface DynamicClient extends SpringCloudDynamicApi {
}
@Component(value = "taskBusinessCallListener")
public class TaskBusinessCallListener implements TaskListener {
/**
* nacos的服务id
*/
private FixedValue serviceId;
/**
* 访问的url路径
*/
private FixedValue url;
/**
* 参数 多个的话用分号隔开 实例 userCode:00004737;status:1
*/
private FixedValue params;
@Autowired
private RuntimeService runtimeService;
@Autowired
private DynamicFeignClientFactory<DynamicClient> dynamicFeignClientFactory;
@Override
public void notify(DelegateTask delegateTask) {
String processInstanceId = delegateTask.getProcessInstanceId();
ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
String businessKey = processInstance.getBusinessKey();
String serviceIdStr = null, urlStr = null, paramsStr = null;
if (serviceId != null) {
serviceIdStr = serviceId.getExpressionText();
}
if (url != null) {
urlStr = url.getExpressionText();
}
if (params != null) {
paramsStr = params.getExpressionText();
}
DynamicClient dynamicClient = dynamicFeignClientFactory.getFeignClient(DynamicClient.class, serviceIdStr, urlStr);
Map<String, String> params = new HashMap<>();
params.put("processInstanceId", processInstanceId);
params.put("businessKey", businessKey);
params.put("params", paramsStr);
dynamicClient.postExecute(params);
}
@SpringBootTest(classes = HopeFlowServerApplication.class)
public class TestClient {
@Autowired
private DynamicFeignClientFactory<DynamicClient> feignClientFactory;
@Test
public void testDynamic() {
DynamicClient dynamicClient = feignClientFactory.getFeignClient(DynamicClient.class, "flow-center", "/api/flow/base/getApps");
Map<String,String> params = new HashMap<>();
JSONObject object = dynamicClient.postExecute(params);
System.out.println(object);
}