Commit a3107b8c authored by Junling Bu's avatar Junling Bu
Browse files

chore[litemall-os-api]: 删除os模块的存储实现,然后依赖core的存储实现

parent 1072fc97
......@@ -22,11 +22,11 @@ public class AllinoneConfigTest {
// 测试获取application-db.yml配置信息
System.out.println(environment.getProperty("spring.datasource.druid.url"));
// 测试获取application-wx.yml配置信息
System.out.println(environment.getProperty("wx.app-id"));
System.out.println(environment.getProperty("litemall.wx.app-id"));
// 测试获取application-admin.yml配置信息
// System.out.println(environment.getProperty(""));
// 测试获取application-os.yml配置信息
System.out.println(environment.getProperty("org.linlinjava.litemall.os.address"));
// System.out.println(environment.getProperty(""));
// 测试获取application.yml配置信息
System.out.println(environment.getProperty("logging.level.org.linlinjava.litemall.os"));
System.out.println(environment.getProperty("logging.level.org.linlinjava.litemall.wx"));
......
package org.linlinjava.litemall.os.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "litemall.os")
public class ObjectStorageConfig {
private String address;
private String port;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
}
package org.linlinjava.litemall.os.service;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.stream.Stream;
/**
* @author Yogeek
* @date 2018/7/16 16:10
* @decrpt 阿里云对象存储服务
*/
@PropertySource(value = "classpath:aliyun.properties")
@Service("aos")
public class AliyunOsService implements ObjectStorageService {
@Value("${aliyun.os.ENDPOINT}")
private String ENDPOINT;
@Value("${aliyun.os.ACCESS_KEY_ID}")
private String ACCESS_KEY_ID;
@Value("${aliyun.os.ACCESS_KEY_SECRET}")
private String ACCESS_KEY_SECRET;
@Value("${aliyun.os.BUCKET_NAME}")
private String BUCKET_NAME;
// @Value("${aliyun.os.FOLDER}")
// private String FOLDER;
/**
* 获取阿里云OSS客户端对象
*
* @return ossClient
*/
private OSSClient getOSSClient(){
return new OSSClient(ENDPOINT,ACCESS_KEY_ID, ACCESS_KEY_SECRET);
}
private String getBaseUrl() {
return "https://" + BUCKET_NAME + "." + ENDPOINT + "/" ;
}
/**
* 阿里云OSS对象存储简单上传实现
*/
@Override
public void store(MultipartFile file, String keyName) {
try {
// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getSize());
objectMetadata.setContentType(file.getContentType());
// 对象键(Key)是对象在存储桶中的唯一标识。
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, keyName, file.getInputStream(), objectMetadata);
PutObjectResult putObjectResult = getOSSClient().putObject(putObjectRequest);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public Stream<Path> loadAll() {
return null;
}
@Override
public Path load(String keyName) {
return null;
}
@Override
public Resource loadAsResource(String keyName) {
try {
URL url = new URL(getBaseUrl() + keyName);
Resource resource = new UrlResource(url);
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
return null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
@Override
public void delete(String keyName) {
try {
getOSSClient().deleteObject(BUCKET_NAME, keyName);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public String generateUrl(String keyName) {
return getBaseUrl() + keyName;
}
}
package org.linlinjava.litemall.os.service;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.*;
import java.util.stream.Stream;
import org.linlinjava.litemall.os.config.ObjectStorageConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
* 服务器本地对象存储服务
*
* 缩写los(local object storage)
*/
@Service("los")
public class LocalOsService implements ObjectStorageService {
@Autowired
private ObjectStorageConfig osConfig;
private static final Path rootLocation = Paths.get("storage");
static {
try {
Files.createDirectories(rootLocation);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void store(MultipartFile file, String keyName) {
try {
Files.copy(file.getInputStream(), LocalOsService.rootLocation.resolve(keyName), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException("Failed to store file " + keyName, e);
}
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(LocalOsService.rootLocation, 1)
.filter(path -> !path.equals(LocalOsService.rootLocation))
.map(path -> LocalOsService.rootLocation.relativize(path));
} catch (IOException e) {
throw new RuntimeException("Failed to read stored files", e);
}
}
@Override
public Path load(String filename) {
return rootLocation.resolve(filename);
}
@Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
return null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
@Override
public void delete(String filename) {
Path file = load(filename);
try {
Files.delete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String generateUrl(String keyName) {
String url = osConfig.getAddress() + ":" + osConfig.getPort() + "/os/storage/fetch/" + keyName;
if (!url.startsWith("http")) {
url = "http://" + url;
}
return url;
}
}
\ No newline at end of file
package org.linlinjava.litemall.os.service;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.stream.Stream;
/**
* 对象存储接口
*/
public interface ObjectStorageService {
/**
* 存储一个文件对象
* @param file SpringBoot MultipartFile文件对象
* @param keyName 文件索引名
*/
void store(MultipartFile file, String keyName);
Stream<Path> loadAll();
Path load(String keyName);
Resource loadAsResource(String keyName);
void delete(String keyName);
String generateUrl(String keyName);
}
\ No newline at end of file
package org.linlinjava.litemall.os.service;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.stream.Stream;
/**
* 腾讯对象存储服务
*
* 注意:虽然腾讯对象存储英文缩写是cos(cloud object storage),但这里称之为tos(tencent object storage)
*/
@PropertySource(value = "classpath:tencent.properties")
@Service("tos")
public class TencentOsService implements ObjectStorageService {
@Value("${tencent.os.secretId}")
private String accessKey;
@Value("${tencent.os.secretKey}")
private String secretKey;
@Value("${tencent.os.region}")
private String region;
@Value("${tencent.os.bucketName}")
private String bucketName;
private COSClient cosClient;
private COSClient getCOSClient() {
if (cosClient == null) {
// 1 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(region));
cosClient = new COSClient(cred, clientConfig);
}
return cosClient;
}
private String getBaseUrl() {
return "https://" + bucketName + ".cos-website." + region + ".myqcloud.com/";
}
@Override
public void store(MultipartFile file, String keyName) {
try {
// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getSize());
objectMetadata.setContentType(file.getContentType());
// 对象键(Key)是对象在存储桶中的唯一标识。例如,在对象的访问域名 `bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg` 中,对象键为 doc1/pic1.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, file.getInputStream(), objectMetadata);
PutObjectResult putObjectResult = getCOSClient().putObject(putObjectRequest);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public Stream<Path> loadAll() {
return null;
}
@Override
public Path load(String keyName) {
return null;
}
@Override
public Resource loadAsResource(String keyName) {
try {
URL url = new URL(getBaseUrl() + keyName);
Resource resource = new UrlResource(url);
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
return null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
@Override
public void delete(String keyName) {
try {
getCOSClient().deleteObject(bucketName, keyName);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public String generateUrl(String keyName) {
return getBaseUrl() + keyName;
}
}
package org.linlinjava.litemall.os.web;
import org.linlinjava.litemall.core.storage.StorageService;
import org.linlinjava.litemall.core.util.CharUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallStorage;
import org.linlinjava.litemall.db.service.LitemallStorageService;
import org.linlinjava.litemall.os.service.ObjectStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
......@@ -24,8 +24,8 @@ import java.util.Map;
@RequestMapping("/os/storage")
public class OsStorageController {
@javax.annotation.Resource(name="${activeStorage}")
private ObjectStorageService storageService;
@Autowired
private StorageService storageService;
@Autowired
private LitemallStorageService litemallStorageService;
......
# 阿里云对象存储配置信息
aliyun.os.ENDPOINT=oss-cn-shenzhen.aliyuncs.com
aliyun.os.ACCESS_KEY_ID=
aliyun.os.ACCESS_KEY_SECRET=
aliyun.os.BUCKET_NAME=
#aliyun.os.FOLDER="xxxxxx"
\ No newline at end of file
# 当前存储模式
# los,本地对象存储模式,上传图片保存在服务器中
# tos,腾讯对象存储模式,上传图片保存在腾讯云存储服务器中,请在tencent.properties配置相关信息
# tos,阿里云对象存储模式,上传图片保存在腾讯云存储服务器中,请在tencent.properties配置相关信息
activeStorage: los
#activeStorage: tos
#activeStorage: aos
# 开发者应该设置成自己的域名,必须附带http或者https
# 开发者可以查看OsStorageController.generateUrl
litemall.os.address: http://127.0.0.1
litemall.os.port: 8081
\ No newline at end of file
# 腾讯对象存储配置信息
# 请参考 https://cloud.tencent.com/document/product/436/6249
tencent.os.secretId="xxxxxx"
tencent.os.secretKey="xxxxxx"
tencent.os.region="xxxxxx"
tencent.os.bucketName="xxxxxx"
package org.linlinjava.litemall.os;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.linlinjava.litemall.os.service.AliyunOsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.FileCopyUtils;
import java.io.FileInputStream;
import java.io.IOException;
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class AosTest {
@Autowired
private AliyunOsService aliyunOsService;
@Test
public void test() throws IOException {
String test = getClass().getClassLoader().getResource("litemall.png").getFile();
byte[] content = (byte[])FileCopyUtils.copyToByteArray(new FileInputStream(test));
MockMultipartFile mockMultipartFile = new MockMultipartFile("litemall.png", "litemall.png", "image/png", content);
aliyunOsService.store(mockMultipartFile, "aos.png");
Resource resource = aliyunOsService.loadAsResource("aos.png");
String url = aliyunOsService.generateUrl("aos.png");
System.out.println("test file " + test);
System.out.println("store file " + resource.getURI());
System.out.println("generate url " + url);
// tencentOsService.delete("aos.png");
}
}
\ No newline at end of file
package org.linlinjava.litemall.os;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.linlinjava.litemall.os.service.LocalOsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.FileCopyUtils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class LosTest {
@Autowired
private LocalOsService localOsService;
@Test
public void test() throws IOException {
String test = getClass().getClassLoader().getResource("litemall.png").getFile();
byte[] content = (byte[])FileCopyUtils.copyToByteArray(new FileInputStream(test));
MockMultipartFile mockMultipartFile = new MockMultipartFile("litemall.png", "litemall.png", "image/jpeg", content);
localOsService.store(mockMultipartFile, "los.png");
Resource resource = localOsService.loadAsResource("los.png");
String url = localOsService.generateUrl("los.png");
System.out.println("test file " + test);
System.out.println("store file " + resource.getURI());
System.out.println("generate url " + url);
// localOsService.delete("los.png");
}
}
\ No newline at end of file
package org.linlinjava.litemall.os;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class OsTest {
@Autowired
Environment environment;
@Test
public void test() {
// 测试获取application-core.yml配置信息
System.out.println(environment.getProperty("litemall.express.appId"));
// 测试获取application-db.yml配置信息
System.out.println(environment.getProperty("spring.datasource.druid.url"));
// 测试获取application-os.yml配置信息
System.out.println(environment.getProperty("litemall.os.address"));
// 测试获取application.yml配置信息
System.out.println(environment.getProperty("logging.level.org.linlinjava.litemall.os"));
}
}
\ No newline at end of file
package org.linlinjava.litemall.os;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.linlinjava.litemall.os.config.ObjectStorageConfig;
import org.linlinjava.litemall.os.service.TencentOsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.FileCopyUtils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class TosTest {
@Autowired
private TencentOsService tencentOsService;
@Test
public void test() throws IOException {
String test = getClass().getClassLoader().getResource("litemall.png").getFile();
byte[] content = (byte[])FileCopyUtils.copyToByteArray(new FileInputStream(test));
MockMultipartFile mockMultipartFile = new MockMultipartFile("litemall.png", "litemall.png", "image/png", content);
tencentOsService.store(mockMultipartFile, "tos.png");
Resource resource = tencentOsService.loadAsResource("tos.png");
String url = tencentOsService.generateUrl("tos.png");
System.out.println("test file " + test);
System.out.println("store file " + resource.getURI());
System.out.println("generate url " + url);
// tencentOsService.delete("tos.png");
}
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment