项目中用到了翻译服务,我们来了解一下有提供翻译服务API。例如:Google Translate API, Microsoft Azure Translator Text API, AWS Translate。
这里我们使用Google Translate API
Google Translate API 是谷歌云平台的一部分,它提供了丰富的功能,包括文本翻译、语音翻译和自动检测语言等。通过简单的 RESTful API 调用,开发者可以在其应用中无缝集成翻译功能,支持超过100种语言的互译。
集成步骤:
1、在Google Cloud Console中创建一个项目。
2、启用Google Translate API。
3、创建服务账户或使用已有的账户,并获取相应的凭证。
4、在Spring Boot项目中pom.xml添加必要的依赖。
<dependencies><dependency><groupId>com.google.cloud</groupId><artifactId>google-cloud-translate</artifactId><version>1.4.0</version></dependency>
</dependencies>
5、配置凭证
在application.properties或application.yml中配置凭证文件路径:
# application.properties
google.application.credentials.location=/path/to/your/credentials-file.json
6、创建一个服务类来使用Google Translate API进行翻译:
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Locale;@Service
public class TranslationService {@Value("${google.application.credentials.location}")private String credentialsLocation;public String translate(String text, String targetLanguage) {try {Translate translate = TranslateOptions.newBuilder().setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(credentialsLocation))).build().getService();Translation translation = translate.translate(text, TranslateOption.targetLanguage(targetLanguage));return translation.getTranslatedText();} catch (IOException e) {e.printStackTrace();return "Error translating text";}}
}
7、创建控制器类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;@RestController
public class TranslationController {private final TranslationService translationService;@Autowiredpublic TranslationController(TranslationService translationService) {this.translationService = translationService;}@GetMapping("/translate")public List<String> translateText(@RequestParam String text, @RequestParam String targetLanguage) throws IOException {List<Translation> translations = translationService.translate(text, targetLanguage);return translations.stream().map(Translation::getTranslatedText).toList();}
}