✅P63_品牌管理-获取服务端签名
大约 4 分钟
新建第三方服务模块
创建模块
New Moudle:cfmall-third-party
勾选“Web”和“OpenFeign”:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gyz.cfmall</groupId>
<artifactId>cfmall-third-party</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cfmall-third-party</name>
<description>第三方服务</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.aliyun.oss/aliyun-sdk-oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>com.gyz.cfmall</groupId>
<artifactId>cfmall-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud alibaba 2.1.0.RELEASE-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
server:
port: 8300
spring:
application:
name: cfmall-third-party
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
alicloud:
access-key: 填写自己的AccessKey ID # AccessKey ID
secret-key: 填写自己的AccessKey Secret # AccessKey Secret
oss:
endpoint: oss-cn-beijing.aliyuncs.com # 阿里云OSS查看自己的region
bootstrap.properties
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.namespace=7e048826-c448-47c7-92e0-e2ff5ed54f8c
# 指明dataId
spring.cloud.nacos.config.extension-configs[0].data-id=oss.yml
# 分组设置,默认组即可
spring.cloud.nacos.config.extension-configs[0].group=DEFAULT_GROUP
# 是否自动刷新配置信息
spring.cloud.nacos.config.extension-configs[0].refresh=true
Nacos新建命名空间并配置
新建命名空间
新增配置内容
spring:
cloud:
alicloud:
access-key: AccessKey ID # 填写自己的AccessKey ID
secret-key: AccessKey Secret #填写自己的AccessKey Secret
oss:
endpoint: oss-cn-beijing.aliyuncs.com
注意:将 cfmall-product
模块的application.yml
中oss配置去掉!
获取服务端签名
服务端签名后直传
代码示例官方地址:应用服务器核心代码解析
OssController.java
:
@Autowired OSS ossClient; ossClient始终为null,识别不到,改用 new OSSClientBuilder().build(xxx)
构造
package com.gyz.cfmall.thirdparty.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.gyz.common.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @Description
* @Author GongYuZhuo
* @Version 1.0.0
*/
@RestController
public class OssController {
// @Autowired(required = false)
// OSS ossClient;
@Value("${spring.cloud.alicloud.oss.endpoint}")
private String endpoint;
@Value("${spring.cloud.alicloud.oss.bucket}")
private String bucket;
@Value("${spring.cloud.alicloud.access-key}")
private String accessId;
@Value("${spring.cloud.alicloud.secret-key}")
private String accessKey;
/**
* Oss 获取服务端签名
*
* @return
*/
@RequestMapping("/oss/policy")
public R policy() {
// https://cfmall-hello.oss-cn-beijing.aliyuncs.com/center.jpg host的格式为 bucketname.endpoint
String host = "https://" + bucket + "." + endpoint;
// callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
// String callbackUrl = "http://88.88.88.88:8888";
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// 用户上传文件时指定的前缀。
String dir = format + "/";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
Map<String, String> respMap = null;
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = ossClient.calculatePostSignature(postPolicy);
respMap = new LinkedHashMap<String, String>();
respMap.put("accessid", accessId);
respMap.put("policy", encodedPolicy);
respMap.put("signature", postSignature);
respMap.put("dir", dir);
respMap.put("host", host);
respMap.put("expire", String.valueOf(expireEndTime / 1000));
// respMap.put("expire", formatISO8601Date(expiration));
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
}
return R.ok().put("data", respMap);
}
}
启动类 CfmallThirdPartyApplication.java
加上服务注册发现注解:@EnableDiscoveryClient
@SpringBootApplication
@EnableDiscoveryClient
public class CfmallThirdPartyApplication {
public static void main(String[] args) {
SpringApplication.run(CfmallThirdPartyApplication.class, args);
}
}
接口测试:http://localhost:8300/oss/policy
配置网关路由
在cfmall-gateway
模块 application.yml
文件中新增第三方服务访问路由
spring:
cloud:
gateway:
routes:
# 见官方文档:https://cloud.tencent.com/developer/article/1403887
- id: third-party_route
uri: lb://cfmall-third-party
predicates:
- Path=/api/thirdparty/**
filters:
- RewritePath=/api/thirdparty/(?<segment>/?.*),/$\{segment}
测试
测试生成的服务签名数据:
获取对象存储的服务端签名数据