SpringBoot integrates Alibaba Cloud OSS to realize image storage service
Alibaba Cloud OSS (Object Storage Service) is a powerful cloud storage service that can be used to store and manage a large number of static files such as pictures, videos, audios, etc. Spring Boot integrates with Alibaba Cloud OSS to realize image upload and storage services, which has the following scenarios and meanings:
-
Distributed storage: Using Alibaba Cloud OSS, static resources such as pictures can be stored in the cloud to realize distributed storage and management. This can improve data availability and reliability, reduce the risk of single point of failure, and ensure that applications can respond quickly in the face of high concurrent access.
-
Elastic expansion: Alibaba Cloud OSS has strong scalability and can automatically expand storage capacity and throughput according to business needs. When the number of users of the application increases and more image upload requests need to be processed, you can rely on the elastic expansion capability of Alibaba Cloud OSS without worrying about system performance bottlenecks.
-
Security guarantee: Alibaba Cloud OSS provides a variety of security mechanisms, such as identity verification, rights management, etc., which can control users' access rights to images stored on OSS. By integrating security frameworks such as Spring Security, access control and permission management of uploaded pictures can be realized to ensure that only authorized users can access and download pictures.
-
Resource proxy and acceleration: Through the CDN (Content Delivery Network) feature of OSS, images stored on OSS can be cached on nodes around the world to accelerate the transmission and loading speed of images. In this way, the user's experience of accessing images can be improved, the waiting time caused by network delays can be reduced, and the performance of the application can be improved.
-
Cost-effectiveness: Using Alibaba Cloud OSS can shift the cost of storing and processing a large number of images to the cloud service provider. OSS provides a flexible billing method, billing according to storage capacity and network traffic, so that developers can control costs according to actual needs, and avoid excessive investment in hardware equipment and maintenance.
The implementation process of this article:
1. Overview of OSS
Object Storage Service (OSS) is a massive, secure, low-cost, and highly reliable cloud storage service suitable for storing any type of file. Elastic expansion of capacity and processing power, multiple storage types to choose from, and comprehensive optimization of storage costs.
Address: https://www.aliyun.com/product/oss
2. Account application
2.1 Purchasing Services
How to purchase subscription services.
Purchase a downstream traffic package: (You can use it without buying it, and pay according to the traffic)
Note: The upstream traffic of OSS is free, but the downstream traffic needs to be purchased.
2.2 Create Buckets
To use OSS, you first need to create a Bucket. Bucket is translated into Chinese as a water bucket. The stored image resources are regarded as water. To hold water, you must have a bucket. Enter the console, https://oss.console.aliyun.com/overview
After selecting Bucket, you can see the corresponding information, such as: url, traffic consumption, etc.:
File management:
View Files:
3. Extract template tool
Alibaba Cloud OSS is packaged in the form of a custom tool
OssProperties configuration class
@Data
@ConfigurationProperties(prefix = "tanhua.oss")
public class OssProperties {
private String accessKey;
private String secret;
private String bucketName;
private String url; //域名
private String endpoint;
}
OssTemplate template object
package com.tanhua.autoconfig.template;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.tanhua.autoconfig.properties.OssProperties;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
public class OssTemplate {
private OssProperties properties;
public OssTemplate(OssProperties properties) {
this.properties = properties;
}
public String upload(String filename, InputStream is) {
// 拼写图片路径
filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
+"/"+ UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
String endpoint = properties.getEndpoint();
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = properties.getAccessKey();
String accessKeySecret = properties.getSecret();
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
// 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
ossClient.putObject(properties.getBucketName(), filename, is);
// 关闭OSSClient。
ossClient.shutdown();
String url = properties.getUrl() +"/" + filename;
return url;
}
}
AutoConfiguration configuration class
@EnableConfigurationProperties({
OssProperties.class
})
public class AutoConfiguration {
@Bean
public OssTemplate ossTemplate(OssProperties properties) {
return new OssTemplate(properties);
}
}
yml configuration content
tanhua: # 都换成自己的
oss:
accessKey: LTAI4GKgob9vZ53k2SZdyAC7
secret: LHLBvXmILRoyw0niRSBuXBZewQ30la
endpoint: oss-cn-beijing.aliyuncs.com
bucketName: tanhua001
url: https://tanhua001.oss-cn-beijing.aliyuncs.com/
4. Test
Write a test class OssTest
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AppServerApplication.class)
public class OssTest {
@Autowired
private OssTemplate template;
@Test
public void testTemplateUpload() throws FileNotFoundException {
String path = "填自己的";
FileInputStream inputStream = new FileInputStream(new File(path));
String imageUrl = template.upload(path, inputStream);
System.out.println(imageUrl);
}
}
Test success:
putStream = new FileInputStream(new File(path));
String imageUrl = template.upload(path, inputStream);
System.out.println(imageUrl);
}
}
测试成功:
![image-20230620091938050](https://img-blog.csdnimg.cn/img_convert/19d705a73cff538552695d9b0d4c5b1c.png)