SpringCloudAlibabaNacos集成阿里云OSS对象存储服务

简介: 首先肯定是开通oss服务了(免费的):

SpringCloudAlibaba整合oss官网示例:https://github.com/alibaba/aliyun-spring-boot/tree/master/aliyun-spring-boot-samples/aliyun-oss-spring-boot-sample

首先肯定是开通oss服务了(免费的):20210212205654555.png

然后创建一个bucket:20210212205912273.png


然后新建一个module,作为专门处理第三方服务的微服务:20210212204542736.png


引入依赖:

<?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.atguigu.gulimall</groupId>
    <artifactId>gulimall-third-party</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>gulimall-third-party</name>
    <description>各种第三方服务</description>
    <parent>
        <groupId>com.atguigu.gulimall</groupId>
        <artifactId>gulimall</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <dependencies>
        <!--里面包含了nacos注册中心和配置中心-->
        <dependency>
            <groupId>com.atguigu.gulimall</groupId>
            <artifactId>gulimall-common</artifactId>
            <exclusions>
                <!--排除mybatis-->
                <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>
<!--        <dependency>-->
<!--            <groupId>com.alibaba.cloud</groupId>-->
<!--            <artifactId>spring-cloud-starter-alicloud-oss</artifactId>-->
<!--        </dependency>-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>aliyun-oss-spring-boot-starter</artifactId>
        </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>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>aliyun-spring-boot-dependencies</artifactId>
                <version>1.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.1.18.RELEASE</version>
                <configuration>
                    <mainClass>com.atguigu.gulimall.thirdparty.GulimallThirdPartyApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


根据图片步骤,进行子账号创建(避免将自己的满权限key暴露在代码里):

20210212214304360.png


赋予oss的读写权限:20210212214632985.png


然后复制好访问key和密钥:

20210212215232415.png


复制endpoint:

20210212215204636.png


来到nacos配置中心,创建个命名空间:

20210212220449168.png


创建配置文件:

20210212222941292.png


创建bootstrap.properties:

# 应用名称
spring.application.name=gulimall-third-party
# 应用服务 WEB 访问端口
server.port=30000
#注册中心
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#配置中心
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
#命名空间
spring.cloud.nacos.config.namespace=91941f1c-d508-4ece-8737-6920bb626206
spring.cloud.nacos.config.ext-config[0].data-id=oss.properties
spring.cloud.nacos.config.ext-config[0].refresh=true


测试:

    @Autowired
    OSSClient ossClient;
    @Test
    public void contextLoads() throws FileNotFoundException {
        FileInputStream in = new FileInputStream("C:\\Users\\baikunlong\\Desktop\\images\\流浪猫狗救助协会_files\\1.jpg");
        ossClient.putObject("bklgulimall","小猫1.jpg",in);
        ossClient.shutdown();
        System.out.println("上传完成");
    }

到这里就能正常上传文件了。


进入主题

经过上面的操作,虽然能上传文件了,但是存在以下问题:

20210212221156393.png


解决方案:

使用服务端签名的方式进行上传:20210212221603164.png


服务端签名,写一个接口:

 package com.atguigu.gulimall.thirdparty.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.atguigu.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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
public class OssController {
    @Autowired
    OSS ossClient;
    @Value("${alibaba.cloud.oss.endpoint}")
    private String endpoint;
    @Value("${alibaba.cloud.oss.bucket}")
    private String bucket;
    @Value("${alibaba.cloud.access-key}")
    private String accessId;
    @RequestMapping("/oss/policy")
    public R policy() {
        //https://gulimall-hello.oss-cn-beijing.aliyuncs.com/hahaha.jpg
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.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 + "/"; // 用户上传文件时指定的前缀。
        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("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);
    }
}


参考官网:https://help.aliyun.com/document_detail/91868.html?spm=a2c4g.11186623.2.10.56077d9cJ5BDOY


访问测试:20210212223230356.png


因为要使用网关统一访问,配置下规则:

        - id: gulimall-third-party
          uri: lb://gulimall-third-party
          predicates:
            - Path=/api/thirdparty/**
          filters:
            - RewritePath=/api/thirdparty/(?<segment>.*),/$\{segment}


重启网关后访问网关88:20210212224112690.png


接下来对接前端:

首先去权限管理下设置允许跨域:20210212225315818.png


然后再搞前端代码。

大致流程为:

1.选择文件

2.请求得到签名

3.上传表单数据

传递如下参数即可:

20210213124755925.png

相关实践学习
对象存储OSS快速上手——如何使用ossbrowser
本实验是对象存储OSS入门级实验。通过本实验,用户可学会如何用对象OSS的插件,进行简单的数据存、查、删等操作。
目录
相关文章
|
11月前
|
云安全 人工智能 安全
Dify平台集成阿里云AI安全护栏,构建AI Runtime安全防线
阿里云 AI 安全护栏加入Dify平台,打造可信赖的 AI
4212 166
|
11月前
|
存储 人工智能 Cloud Native
阿里云渠道商:OSS与传统存储系统的差异在哪里?
本文对比传统存储与云原生对象存储OSS的架构差异,涵盖性能、成本、扩展性等方面。OSS凭借高持久性、弹性扩容及与云服务深度集成,成为大数据与AI时代的优选方案。
|
存储 运维 安全
阿里云国际站OSS与自建存储的区别
阿里云国际站对象存储OSS提供海量、安全、低成本的云存储解决方案。相比自建存储,OSS具备易用性强、稳定性高、安全性好、成本更低等优势,支持无限扩展、自动冗余、多层防护及丰富增值服务,助力企业高效管理数据。
|
存储 域名解析 前端开发
震惊!不买服务器,还可以用阿里云国际站 OSS 轻松搭建静态网站
在数字化时代,利用阿里云国际站OSS可低成本搭建静态网站。本文详解OSS优势及步骤:创建Bucket、上传文件、配置首页与404页面、绑定域名等,助你快速上线个人或小型业务网站,操作简单,成本低廉,适合初学者与中小企业。
|
弹性计算 运维 安全
云迁移最佳实践:HyperMotion助中小企业高效上云,阿里云工具集深度集成三方迁移工具
中小企业上云需求强烈,但面临缺乏了解、无合适方案及成本过高等挑战。为解决这些问题,推出“云迁移HyperMotion阿里云集成版”,提供三步上云、自助迁移、自动适配等能力,助力企业高效、低成本完成迁移。
395 0
|
存储 弹性计算 数据管理
阿里云OSS对象存储收费标准价格表:流量包+存储包2025最新整理
阿里云OSS对象存储2025收费标准及请求费用等,提供按量付费与包年包月两种模式。标准型本地冗余存储按量价为0.09元/GB/月,包年包月如500GB仅118.99元/年。流量费仅收公网出方向,闲时0.25元/GB、忙时0.5元/GB。更多详情见官网。
6226 2
|
安全 持续交付 云计算
课时5:阿里云容器服务:最原生的集成Docker和云服务
阿里云容器服务以服务化形式构建容器基础设施,大幅提升开发效率,简化应用部署流程。通过Docker容器和DevOps工具(如Jenkins),实现自动化部署与迭代,优化企业内部复杂部署问题。该服务支持GPU调度、混合云架构无缝迁移,并与阿里云产品体系无缝集成,提供安全防护、网络负载均衡等多重功能支持。凭借微服务架构,帮助企业突破业务瓶颈,提高资源利用率,轻松应对海量流量。
586 0
课时5:阿里云容器服务:最原生的集成Docker和云服务
|
人工智能 自然语言处理 搜索推荐
阿里云 AI 搜索开放平台集成 DeepSeek 模型
阿里云 AI 搜索开放平台最新上线 DeepSeek -R1系列模型。
1062 2
|
SQL 分布式计算 Serverless
基于阿里云 EMR Serverless Spark 版快速搭建OSS日志分析应用
基于阿里云 EMR Serverless Spark 版快速搭建OSS日志分析应用
462 0