没关注?伸出手指点这里---
本篇文章主要讲述如何在本地代码中调用部署在华为云ModelArts平台的垃圾分类预测模型的API接口,实现上传图片即可识别垃圾类别(日常生活垃圾识别率0.9以上,识别率取决于预测模型)。
完整Demo参考:https://github.com/servicestage-demo/cse-java-demo-list/tree/master/demo-cse-garbage-classify
创建工程
1
首先在本地搭建ServiceComb工程
为了能够使开发者可以快速构建ServiceComb应用程序,官方为我们提供了一套脚手架,这样能够方便学习者及应用开发者快速入门,同时极大的提高了效率。
快速开发引导页:http://start.servicecomb.io/
填写好工程group、artifact等信息(ServiceComb参数可以使用默认),就可以生成一个ServiceComb工程了,将工程下载到本地,导入到Eclipse或者IDEA等开发工具中。
2
配置microservice.yaml
servicecomb.service.registry.address:CSE(微服务引擎)服务注册发现地址
servicecomb.rest.address:本地应用访问地址
AK、SK获取请参考链接:https://support.huaweicloud.com/devg-apisign/api-sign-provide.html#p3
APPLICATION_ID: demo-face-recognition
service_description:
# name of the declaring microservice
name: demo-face-recognition
version: 0.0.1
environment: development
servicecomb:
service:
registry:
address: https://cse.xxx.myhuaweicloud.com:port
rest:
address: 0.0.0.0:8081
credentials:
accessKey: Your AK
secretKey: Your SK
project: cn-north-1
akskCustomerCipher: default
handler:
chain:
Provider:
default: tracing-provider
也可以使用本地注册中心,到官网http://servicecomb.apache.org/cn/release/下载ServiceComb Service-Center(选最新版本)
本地microservice.yaml配置参考:
APPLICATION_ID: demo-face-recognition
service_description:
name: demo-face-recognition
version: 1.0.0
service_description:
name: demo-provider
version: 1.0.0
servicecomb:
rest:
address: 0.0.0.0:9000
service:
registry:
address: http://127.0.0.1:30100
3
配置application.properties(与microservice.yaml同目录)
图片保存路径:自定义
获取token参数:[参考Token认证鉴权指南]https://support.huaweicloud.com/api-modelarts/modelarts_03_0004.html
ModelArts API接口地址:[参考ModelArts使用指南]https://support.huaweicloud.com/engineers-modelarts/modelarts_23_0001.html
#图片保存路径
gc_img_path=/usr/gc/img/
#获取token参数
gc_token_url=https://xxx.myhuaweicloud.com/v3/auth/tokens
gc_token_username=username
gc_token_password=password
gc_token_domain=domain
gc_token_project=project
#ModelArts API接口地址
gc_api_url=ModelArts_api_url
4
定义接口
定义了垃圾分类识别接口
public interface GCEndpoint {
/**
* garbage-classify
*/
String gc(MultipartFile file);
}
5
编写业务类
访问路径可以自定义,注意参数类型是file(直接上传图片进行识别)
package org.apache.servicecomb.samples.gc;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
/**
* {@link GCRestEndpoint} provides the rest implementation of
* {@link GCEndpoint}. The rest endpoint is accessed by /gc with HTTP POST.
*/
@RestSchema(schemaId = "GCRestEndpoint")
@RequestMapping(path = "/")
public class GCRestEndpoint implements GCEndpoint {
private final FileService fileService;
@Autowired
public GCRestEndpoint(FileService fileService) {
this.fileService = fileService;
}
@PostMapping(path = "/gc", produces = MediaType.TEXT_PLAIN_VALUE)
public String gc(@RequestPart(name = "file") MultipartFile file) {
return fileService.uploadFile(file);
}
}
6
实现获取Token,调用人脸识别API
为避免频繁调用获取Token接口,可以在本地缓存Token,Token有效期是24小时。
package org.apache.servicecomb.samples.gc;
import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.servicecomb.provider.springmvc.reference.RestTemplateBuilder;
import org.apache.servicecomb.tracing.Span;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@Service
public class FileServiceImpl implements FileService {
private static final String TOKEN_KEY = "X-Subject-Token";
private static final String EXPIRES_KEY = "Expires-time";
private static final long availablePeriod = 20 * 3600 * 1000; // 每20小时获取一次token
private static Map<String, String> tokenMap = new HashMap<String, String>();
private static Logger LOGGER = Logger.getLogger(FileServiceImpl.class);
@Value("${gc_img_path}")
private String gcImgPath;
@Value("${gc_token_url}")
private String gcTokenUrl;
@Value("${gc_token_username}")
private String gcTokenUsername;
@Value("${gc_token_password}")
private String gcTokenPassword;
@Value("${gc_token_domain}")
private String gcTokenDomain;
@Value("${gc_token_project}")
private String gcTokenProject;
@Value("${gc_api_url}")
private String gcApiUrl;
private String getToken() {
LOGGER.info("start to get token");
if (!tokenMap.isEmpty()) {
long startTime = Long.valueOf(tokenMap.get(EXPIRES_KEY));
long currTime = System.currentTimeMillis();
if (currTime - startTime < availablePeriod) {
return tokenMap.get(TOKEN_KEY);
}
}
String raw = requestBody(gcTokenUsername, gcTokenPassword, gcTokenDomain, gcTokenProject);
RestTemplate restTemplate = RestTemplateBuilder.create();
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
HttpEntity<String> entity = new HttpEntity<String>(raw, headers);
ResponseEntity<String> r = restTemplate.postForEntity(gcTokenUrl, entity, String.class);
String token = r.getHeaders().getFirst(TOKEN_KEY);
tokenMap.put(TOKEN_KEY, token);
tokenMap.put(EXPIRES_KEY, String.valueOf(System.currentTimeMillis()));
LOGGER.info("end to get token");
return token;
}
/**
* 构造使用Token方式访问服务的请求Token对象
*
* @param username 用户名
* @param passwd 密码
* @param domainName 域名
* @param projectName 项目名称
* @return 构造访问的JSON对象
*/
private static String requestBody(String username, String passwd, String domainName, String projectName) {
JSONObject auth = new JSONObject();
JSONObject identity = new JSONObject();
JSONArray methods = new JSONArray();
methods.add("password");
identity.put("methods", methods);
JSONObject password = new JSONObject();
JSONObject user = new JSONObject();
user.put("name", username);
user.put("password", passwd);
JSONObject domain = new JSONObject();
domain.put("name", domainName);
user.put("domain", domain);
password.put("user", user);
identity.put("password", password);
JSONObject scope = new JSONObject();
JSONObject scopeProject = new JSONObject();
scopeProject.put("name", projectName);
scope.put("project", scopeProject);
auth.put("identity", identity);
auth.put("scope", scope);
JSONObject params = new JSONObject();
params.put("auth", auth);
return params.toJSONString();
}
@Span
@Override
public String uploadFile(MultipartFile file) {
LOGGER.info("start to upload file");
String filePath = null;
String imgName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
if (file != null && !file.isEmpty()) {
// 文件保存路径
filePath = gcImgPath + imgName;
// 转存文件
try {
file.transferTo(new File(filePath));
} catch (Exception e) {
return e.getMessage();
}
}
if (filePath == null) {
return "{\"result\": \"不可回收物/有害物品\"}";
}
RestTemplate restTemplate = getRestTemplate("UTF-8");
// 设置请求头
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("multipart/form-data;charset=UTF-8;");
headers.setContentType(type);
headers.set("X-Auth-Token", getToken());
// 设置请求体,注意是LinkedMultiValueMap
MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
FileSystemResource fileSystemResource = new FileSystemResource(filePath);
form.add("input_img", fileSystemResource);
// 用HttpEntity封装整个请求报文
HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<MultiValueMap<String, Object>>(form, headers);
ResponseEntity<String> s = restTemplate.postForEntity(gcApiUrl, files, String.class);
LOGGER.info("end to upload file");
return s.getBody();
}
public static RestTemplate getRestTemplate(String charset) {
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
for (HttpMessageConverter<?> httpMessageConverter : list) {
if (httpMessageConverter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName(charset));
break;
}
}
return restTemplate;
}
}
7
调用示例
#垃圾分类识别接口
请求URL:http://xxx.xxx.213.158:8081/gc
请求方式:POST
参数类型:body
参数示例:form-data (key:file, value:[图片文件])
返回示例:{"result": "不可回收物/有害物品"}
8
pom.xml参考
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.apache.servicecomb.samples</groupId>
<artifactId>garbage-classify</artifactId>
<name>Java Chassis::Samples::Garbage-Classify</name>
<version>1.2.0</version>
<packaging>jar</packaging>
<description>Quick Start Demo for Using ServiceComb Java Chassis</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<java-chassis.version>${project.version}</java-chassis.version>
<spring-boot-1.version>1.5.14.RELEASE</spring-boot-1.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.servicecomb</groupId>
<artifactId>java-chassis-dependencies</artifactId>
<version>${java-chassis.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot-1.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.servicecomb</groupId>
<artifactId>spring-boot-starter-provider</artifactId>
</dependency>
<dependency>
<groupId>org.apache.servicecomb</groupId>
<artifactId>handler-flowcontrol-qps</artifactId>
</dependency>
<dependency>
<groupId>org.apache.servicecomb</groupId>
<artifactId>handler-bizkeeper</artifactId>
</dependency>
<dependency>
<groupId>org.apache.servicecomb</groupId>
<artifactId>handler-tracing-zipkin</artifactId>
</dependency>
<dependency>
<groupId>com.huawei.paas.cse</groupId>
<artifactId>cse-solution-service-engine</artifactId>
<version>2.3.56</version>
</dependency>
<dependency>
<groupId>org.apache.servicecomb</groupId>
<artifactId>tracing-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.14</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
${project.build.directory}/dtm-lib
</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>./dtm-lib/</classpathPrefix>
<mainClass>org.apache.servicecomb.samples.gc.GCApplication</mainClass>
<useUniqueVersions>false</useUniqueVersions>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<compilerArgument>-parameters</compilerArgument>
<encoding>UTF-8</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
如您对开源开发、微服务感兴趣
欢迎扫描下方二维码添加
ServiceComb小助手
咱们一起做点有意思的事情~
关注我们获取更多精彩内容
在看一点,病毒退散