使用springboot实现阿里云照片缓存
时间: 2024-05-25 15:05:00 浏览: 163
要使用Spring Boot实现阿里云照片缓存,首先需要在阿里云上创建一个OSS(对象存储服务)实例,然后在Spring Boot应用中使用阿里云提供的Java SDK进行开发。
以下是一个简单的示例,演示如何在Spring Boot应用中使用阿里云OSS服务缓存照片:
1. 首先,需要在Spring Boot应用的pom.xml文件中添加阿里云Java SDK的依赖:
```
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
```
2. 在application.properties文件中添加阿里云OSS的配置信息:
```
aliyun.oss.endpoint=your-oss-endpoint
aliyun.oss.accessKeyId=your-access-key-id
aliyun.oss.accessKeySecret=your-access-key-secret
aliyun.oss.bucketName=your-bucket-name
```
3. 创建一个AliyunOSSService类,用于将照片上传到阿里云OSS,并从OSS中获取照片:
```java
@Service
public class AliyunOSSService {
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
private OSS ossClient;
public void init() {
ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
public void destroy() {
ossClient.shutdown();
}
public String uploadPhoto(InputStream inputStream, String contentType, String fileName) {
try {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(contentType);
ossClient.putObject(bucketName, fileName, inputStream, metadata);
return ossClient.generatePresignedUrl(bucketName, fileName, new Date(System.currentTimeMillis() + 3600 * 1000)).toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public InputStream getPhoto(String fileName) {
try {
OSSObject object = ossClient.getObject(bucketName, fileName);
return object.getObjectContent();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
4. 在Spring Boot应用中使用AliyunOSSService类进行照片上传和获取:
```java
@RestController
public class PhotoController {
@Autowired
private AliyunOSSService aliyunOSSService;
@PostMapping("/photos")
public String uploadPhoto(@RequestParam("file") MultipartFile file) {
try {
String photoUrl = aliyunOSSService.uploadPhoto(file.getInputStream(), file.getContentType(), file.getOriginalFilename());
return photoUrl;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@GetMapping("/photos/{fileName}")
public ResponseEntity<byte[]> getPhoto(@PathVariable("fileName") String fileName) {
try {
InputStream inputStream = aliyunOSSService.getPhoto(fileName);
byte[] bytes = IOUtils.toByteArray(inputStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
以上示例演示了如何在Spring Boot应用中使用阿里云OSS服务缓存照片。可以根据自己的实际需求进行修改和扩展。
阅读全文