1. 程式人生 > 其它 >穀粒商城筆記-環境配置(2)——檔案上傳、java引數驗證、遞迴,分頁、事務

穀粒商城筆記-環境配置(2)——檔案上傳、java引數驗證、遞迴,分頁、事務

gulimall 檔案儲存,引數校驗,程式設計中常用語法

18.阿里雲OSS檔案上傳功能

18.1 建立三方服務

  • 建立微服務gulimall-third-part:

組織名:com.atguigu.gulimall;模組名:gulimall-third-part;包名:com.atguigu.gulimall.thirdpart

Name:gulimall.thirdpart 。之後在下一步的依賴中新增web—>spring web,Spring Cloud Routing—> open Feign

  • 新增公用配置依賴:

a.新增common 公共依賴

View Code

b.nacos註冊中心,配置中心

註冊中心: 新增pom引用(common中包含),新建配置檔案(bootstrap.properties)新增配置,開啟註冊中心(在啟動服務main函式類上)@EnableDiscoveryClient

配置檔案:

spring.application.name=gulimall-third-part

spring.cloud.nacos.config.server-addr=127.0.0.1:8848

server.port= 88

18.2OSS阿里雲端儲存

分散式系統中的檔案儲存:https://www.jianshu.com/p/1be6bf51566f

阿里雲教程:https://help.aliyun.com/learn/learningpath/oss.html?spm=5176.7933691.J_7985555940.3.53e94c59v339me

阿里雲使用使用官網:https://help.aliyun.com/document_detail/32009.html

  1. 登入阿里雲賬號,進入物件儲存介面(物件儲存OSS)
  2. 在Bucket 列表建立一個gulimaill-hello2的bucket,建立過程中需要的引數介紹:https://help.aliyun.com/document_detail/31827.html

3.建立訪問金鑰 在滑鼠放到使用者頭像顯示的AccessKey 管理——>選擇開始使用子使用者管理AccessKey——>建立使用者名稱與顯示名都為gulimall的使用者之後, 訪問方式Open API 呼叫訪問——為新使用者新增許可權——>建立新的AccessKey,之後儲存id與密碼。

AliyunOSSFullAccess

管理物件儲存服務(OSS)許可權

4.用檔案上傳方式上傳檔案:參考地址:https://help.aliyun.com/document_detail/84781.html

本次嘗試使用的是上傳檔案流;

View Code

18.3Spring Alibaba OSS 封裝的元件

Spring Alibaba OSS 封裝的元件:https://github.com/alibaba/aliyun-spring-boot/tree/master/aliyun-spring-boot-samples/aliyun-oss-spring-boot-sample

1、新增pom檔案的引用

<dependency>

<groupId>com.alibaba.cloud</groupId>

<artifactId>aliyun-oss-spring-boot-starter</artifactId>

</dependency>

2、在配置檔案中.直接新增配置

// application.properties

alibaba.cloud.access-key=your-ak

alibaba.cloud.secret-key=your-sk

alibaba.cloud.oss.endpoint=***

3、在微服務中的呼叫: OSSClient 以服務註冊的方式注入。

@Service
 public class YourService {
     @Autowired
     private OSSClient ossClient;

     public void saveFile() {
                 String bucketName = "gulimaill-hello2";
// 填寫本地檔案的完整路徑。如果未指定本地路徑,則預設從示例程式所屬專案對應本地路徑中上傳檔案流。
        InputStream inputStream = new FileInputStream("/D:\\testa2.txt");
// 依次填寫Bucket名稱(例如examplebucket)和Object完整路徑(例如exampledir/exampleobject.txt)。Object完整路徑中不能包含Bucket名稱。
        ossClient.putObject(bucketName, "testa2.txt", inputStream);

     }
 }
View Code

4、配置檔案配置在nacos配置中心中

根據nacos中的配置,配置成配置檔案

spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.namespace=d3791198-6eea-45e8-8e33-8e1a37bc5f34

spring.cloud.nacos.config.ext-config[0].data-id=gulimall-third-part-oss.yml
spring.cloud.nacos.config.ext-config[0].group=DEFAULT_GROUP
spring.cloud.nacos.config.ext-config[0].refresh=true

18.4 分散式系統中的檔案上傳模型

參考文件:https://help.aliyun.com/document_detail/31926.html

1、伺服器模擬policy,微服務中生成一個通用方法

@RestController
public class OSSController {
    @Autowired
    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;
   
    @RequestMapping("/oss/policy")
    public   Map<String, String>  doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       /* String accessId = "<yourAccessKeyId>"; // 請填寫您的AccessKeyId。
        String accessKey = "<yourAccessKeySecret>"; // 請填寫您的AccessKeySecret。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com"; // 請填寫您的 endpoint。*/
        //String bucket = "bucket-name"; // 請填寫您的 bucketname 。
        String host = "https://" + bucket + "." + endpoint; // host的格式為 bucketname.endpoint
        // callbackUrl為上傳回調伺服器的URL,請將下面的IP和Port配置為您自己的真實資訊。
        //String callbackUrl = "http://88.88.88.88:8888";
        //修改為按照時間格式的方式
        String dateFormat=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir =dateFormat+"/"; // 使用者上傳檔案時指定的字首。
        // 建立OSSClient例項。
        //OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        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));
            // respMap.put("expire", formatISO8601Date(expiration));

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return  respMap;
    }
}
View Code

2、測試結果:

呼叫連結:http://localhost:30000/oss/policy

返回結果:

{"accessid":"LTAI5tEVEUcQMFAYHM1p1Rwe","policy":"etJleHBpcmF0aW9uIjoiMjAyMS0xMC0wNVQwMjoyNDo1Mi4xNThaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCIyMDIxLTEwLTA1LyJdXX0=","signature":"/j/0l4ZFpq2MQ4rSGCBsL4tt6N4=","dir":"2021-10-05/","host":"https://gulimaill-hello2.oss-cn-shanghai.aliyuncs.com","expire":"1633400692"}

3、閘道器配置:

policy的連結訪問統一從:http://localhost:88/api/thirdpart/oss/policy

在閘道器配置中新增:

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

19.JAVA引數校驗(Valid,Validated,自定義檢驗)