微服务现在已经被众多厂商接受,但是大家对以前的一些在线服务能否持续使用还存在疑惑,consul微服务治理平台就提供了一种极简的集成方式,使得基于Http(s)协议的服务都可以方便的集成到一个平台上,和其他原生的微服务无差异使用,下面就实施步骤逐一说明。
注册成为微服务
要以微服务的方式调用这些第三方服务,首先要将这些服务注册到consul上,可以使用命令行的方式,也可以编写一个简单的java程序实现。
@RestController
public class ConsulServiceController {
private static Logger log = LoggerFactory.getLogger(ConsulServiceController.class);
@Autowired
private ConsulClient consulClient;
@RequestMapping(value = "/regservice", method = RequestMethod.POST)
@ApiOperation(value = "注册第三方API成为服务", notes = "注册第三方API")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "id", value = "微服务ID", required = true, dataType = "String"),
@ApiImplicitParam(paramType = "query", name = "tag", value = "商用逗号分隔的标签", required = true, dataType = "String"),
@ApiImplicitParam(paramType = "query", name = "name", value = "微服务唯一名称", required = true, dataType = "String"),
@ApiImplicitParam(paramType = "query", name = "port", value = "微服务端口号", required = true, dataType = "int"),
@ApiImplicitParam(paramType = "query", name = "domain", value = "API域名或者IP", required = true, dataType = "String"),
@ApiImplicitParam(paramType = "query", name = "healthUrl", value = "API健康监测地址", dataType = "String")
})
public Boolean registerService(@RequestParam(value = "id") String serviceID, @RequestParam(value = "tag") String tag, @RequestParam(value = "name") String serviceName, @RequestParam(value = "port") int port, @RequestParam(value = "domain") String domain, @RequestParam(value = "healthUrl", required = false) String healthUrl) {
//判断serviceName或者serviceID是否已经存在
List<Member> members = consulClient.getAgentMembers().getValue();
for (int i = 0; i < members.size(); i++) {
String role = members.get(i).getTags().get("role");
//判断是否为client
if (role.equals("node")) {
String address = members.get(i).getAddress();
//将IP地址传给ConsulClient的构造方法,获取对象
ConsulClient clearClient = new ConsulClient(address);
//根据clearClient,获取当前IP下所有的服务 使用迭代方式 获取map对象的值
Iterator<Map.Entry<String, Service>> it = clearClient.getAgentServices().getValue().entrySet().iterator();
while (it.hasNext()) {
//迭代数据
Map.Entry<String, Service> serviceMap = it.next();
//获得Service对象
Service service = serviceMap.getValue();
if (serviceID.equalsIgnoreCase(service.getId()) || serviceName.equalsIgnoreCase(service.getService())) {
return false;
}
}
}
}
//组装服务信息
List<String> tags = Arrays.asList(tag.split(","));
NewService newService = new NewService();
newService.setId(serviceID);
newService.setTags(tags);
newService.setName(serviceName);
newService.setPort(port);
newService.setAddress(domain);
//组装健康检查信息
if (healthUrl != null) {
NewService.Check serviceCheck = new NewService.Check();
serviceCheck.setHttp(healthUrl);
serviceCheck.setInterval("30s");
newService.setCheck(serviceCheck);
}
consulClient.agentServiceRegister(newService);
return true;
}
}
注册成功后就可以在consul UI中看到你注册的微服务。
无差异调用第三方微服务
第三方微服务在consul平台上和原生微服务是一样的使用方式,也就是通过springcloud的Feign的接口引用。
- 先定义第三方服务的接口
import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@FeignClient(name = "baidu-api")
public interface IBaiduApi {
@GetMapping(value = "/oauth/2.0/token")
JSONObject getAccessToken(@RequestParam("grant_type") String grant_type, @RequestParam("client_id") String client_id, @RequestParam("client_secret") String client_secret);
@PostMapping(value = "/rest/2.0/image-classify/v2/advanced_general",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
JSONObject getObjectInfo(@RequestParam("access_token") String access_token,@RequestBody String image);
@PostMapping(value = "/rest/2.0/image-classify/v1/car",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
JSONObject getCarInfo(@RequestParam("access_token") String access_token,@RequestBody String image);
@PostMapping(value = "/rest/2.0/ocr/v1/idcard",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
JSONObject getIDCardInfo(@RequestParam("access_token") String access_token,@RequestParam("id_card_side") String side,@RequestBody String image);
@PostMapping(value = "/rest/2.0/ocr/v1/accurate_basic",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
JSONObject getImageTextInfo(@RequestParam("access_token") String access_token,@RequestBody String image);
@PostMapping(value = "/rest/2.0/face/v3/detect?image_type=BASE64&max_face_num=10",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
JSONObject getFaceInfo(@RequestParam("access_token") String access_token,@RequestBody String image);
}
- 在调用的部分通过@Autowired注入该接口
@Autowired
private IBaiduApi baiduApi;
- 直接调用接口方法
@PostMapping(value = "/baiduAI/Car")
@ApiOperation(value = "百度图像识别-汽车品牌", notes = "使用百度AI识别图像")
public JSONObject getBaiduAIInfo(@RequestPart("file") MultipartFile file) throws IOException {
JSONObject result = baiduAIImageBase64(baiduAIConf.getImage().get("clientId"), baiduAIConf.getImage().get("clientSecret"), file);
if (!result.isEmpty()) {
return baiduApi.getCarInfo(result.getString("token"), "image=" + result.getString("base64"));
}
return null;
}