二十四.项目整合OSS服务

一.引入OSS依赖

OSS是第三方服务,而以后肯定还是会有很多第三方的服务需要引入,所以新建一个第三方模块webshop-third-party做一个整合,webshop-third-party模块的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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.jiejie.webshop</groupId>
    <artifactId>webshop-third-party</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>webshop-third-party</name>
    <description>第三方服务</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR3</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.jiejie.webshop</groupId>
            <artifactId>webshop-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </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>
        <!--oss存储服务-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </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>
            <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>

同时把webshop-third-party模块整合到项目中:
二十四.项目整合OSS服务_第1张图片

二.修改webshop-third-party项目配置

先把webshop-third-party项目注册进注册中心中,同时加上使用OSS服务需要的配置属性,application.yml文件信息如下:

#第三方服务端口号
server:
  port: 30000
#服务名,注册中心,oss相关配置
spring:
  application:
    name: webshop-third-party
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1
    alicloud:
      oss:
        endpoint: oss-cn-hangzhou.aliyuncs.com
      access-key: LTAI4G9WxXN3MmQ1EETv28Ev
      secret-key: mlMSCDoWW24TD1E5qIUiU7XbJZr0Lr

oss服务的配置信息从可以在如下截图中找到:
在这里插入图片描述
二十四.项目整合OSS服务_第2张图片
启动类加上服务注册和发现注解@EnableDiscoveryClient以及先去除数据源自动配置,如下:

@EnableDiscoveryClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class WebshopThirdPartyApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebshopThirdPartyApplication.class, args);
    }
}

三.编写一个接口测试下OSS

这里采用服务端签名后直传的方式,不会对服务端产生压力,而且安全可靠,服务端签名后直传简单的理解就是比如用户要上传文件,会先上传Policy给服务端,服务端会返回一个上传Policy和签名给用户,然后用户就可以上传数据到OSS了。

编写签名接口,如下:

package com.jiejie.webshop.thirdparty.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/oss")
public class OssController {
    @Autowired
    private OSS ossClient;
    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;
    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @GetMapping("/policy")
    public Map<String, String> policy() {
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        // callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
//        String callbackUrl = "http://88.88.88.88:8888";
        //以日期为前缀
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = date + "/"; // 用户上传文件时指定的前缀。
        Map<String, String> respMap = new LinkedHashMap<String, String>();
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            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("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            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));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return respMap;
    }
}

网关层配上相应路由:
二十四.项目整合OSS服务_第3张图片

四.测试接口

根据配置的路由规则,浏览器输入http://localhost:88/api/thirdparty/oss/policy访问签名接口,结果如下:
在这里插入图片描述
能成功返回签名。

你可能感兴趣的:(从零开始搭建一个电商系统)