阿里云oss
用户认证需要上传证件图片、首页轮播也需要上传图片,因此我们要做文件服务,阿里云oss是一个很好的分布式文件服务系统,所以我们只需要集成阿里云oss即可。
1、开通“对象存储OSS”服务
(1)申请阿里云账号
(2)实名认证
(3)开通“对象存储OSS”服务
(4)进入管理控制台
1.1、创建Bucket
选择:
创建成功:
1.2、上传默认头像
创建文件夹avatar,上传默认的用户头像
上传到阿里云oss的文件:
1.3、获取用户acesskeys,后续需要使用该值
2、阿里云oss使用SDK文档
3、文件上传服务的实现
3.1、搭建service-oss模块
搭建过程参考service-user模块
3.2、修改配置
1、修改pom.xml,引入阿里云oss依赖
<dependencies>
<!-- 阿里云oss依赖 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!-- 日期工具栏依赖 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
<version>2.2.6.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.9.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
2、添加配置文件application.properties
# 服务端口
server.port=8205
# 服务名
spring.application.name=service-oss
#返回json的全局时间格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
# nacos服务地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# 地域节点
aliyun.oss.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.sms.accessKeyId=你的sccessKeyId
aliyun.sms.secret=你的secret
aliyun.oss.bucket=你的bucket名(yygh)
3.3、启动类
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//配置文件中没有数据库信息,这里取消数据源自动配置
@EnableDiscoveryClient//将服务注册到nacos服务中心
@ComponentScan(basePackages = {"com.study"})
public class ServiceOssApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceOssApplication.class, args);
}
}
3.4、配置网关
# 阿里云文件存储服务(证件照上传模块)
#设置路由id
spring.cloud.gateway.routes[5].id=service-oss
#设置路由的uri
spring.cloud.gateway.routes[5].uri=lb://service-oss
#设置路由断言,代理servicerId为auth-service的/auth/路径
spring.cloud.gateway.routes[5].predicates= Path=/*/oss/**
3.5、小测:编写代码,测试SDK
(为了测试前面配置是否正确)
(使用阿里云官方代码测试在oss上创建bucket)
/**
* @Description :使用阿里云官方代码测试创建OSSClient
* @Author :lenovo
* @Date :2021/7/24 19:28
*/
public class OssTest {
public static void main(String[] args) {
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "<你的地域节点>";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
String accessKeyId = "你的accessKeyId";
String accessKeySecret = "你的accessKeySecret";
String bucketName = "你要创建的bucket文件名";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//创建存储空间
ossClient.createBucket(bucketName);
// 关闭OSSClient。
ossClient.shutdown();
}
}
3.6、封装service
1、接口:
public interface MsnService {
//发送手机验证码
public boolean send(String phone, String code);
}
2、实现类
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.study.yygh.oss.service.FileService;
import com.study.yygh.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Service
public class MsnServiceImpl implements MsnService {
//发送手机验证码
@Override
public boolean send(String phone, String code) {
//判断手机号是否为空
if(StringUtils.isEmpty(phone)) {
return false;
}
//整合阿里云短信服务
//设置相关参数
DefaultProfile profile = DefaultProfile.
getProfile(ConstantPropertiesUtils.REGION_ID,
ConstantPropertiesUtils.ACCESS_KEY_ID,
ConstantPropertiesUtils.SECRECT);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
//request.setProtocol(ProtocolType.HTTPS);
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
//手机号
request.putQueryParameter("PhoneNumbers", phone);
//签名名称
request.putQueryParameter("SignName", "我的谷粒在线教育网站");
//模板code
request.putQueryParameter("TemplateCode", "SMS_180051135");
//验证码 使用json格式 {"code":"123456"}
Map<String,Object> param = new HashMap();
param.put("code",code);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
//调用方法进行短信发送
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
return response.getHttpResponse().isSuccess();
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
}
3.7、配置工具类
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @Description :配置类
* @Author :lenovo
* @Date :2021/7/22 22:56
*/
@Component
public class ConstantOssPropertiesUtils implements InitializingBean {
@Value("${aliyun.oss.endpoint}")
public String endpoint;
@Value("${aliyun.oss.accessKeyId}")
public String accessKeyId;
@Value("${aliyun.oss.secret}")
public String secret;
@Value("${aliyun.oss.bucket}")
public String bucket;
public static String ENDPOINT;
public static String ACCESS_KEY_ID;
public static String SECRECT;
public static String BUCKET;
@Override
public void afterPropertiesSet() {
ENDPOINT=endpoint;
ACCESS_KEY_ID=accessKeyId;
SECRECT=secret;
BUCKET=bucket;
}
}
3.8、封装controller接口
import com.study.yygh.common.result.Result;
import com.study.yygh.oss.service.impl.FileServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/oss/file")
public class FileApiController {
@Autowired
private FileServiceImpl fileService;
//上传文件到阿里云
@PostMapping("fileUpload")
public Result fileUpload(MultipartFile file){
//获取到上传的文件
String url = fileService.upload(file);
return Result.ok(url);
}
}
3.9、使用swagger测试文件上传到阿里云oss的功能接口
阿里云oss: