AmazonS3部署以及nacos配置参数

news2024/9/17 9:12:53

AmazonS3部署

因为涉及到做的需求的头像的处理,所以需要去找头像的来源,没想到又是我们的老熟人,AmazonS3,巧了已经是第二次用了,上次我是用的别人的工具类去干的,这一次我这边自己编辑具体工具类型。
对应的依赖

        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.358</version>
        </dependency>
        

具体的工具类

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.RegionUtils;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.*;
import lombok.extern.slf4j.Slf4j;


import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class AmazonS3FileUtils {

	private static String bucketName = null;
    private static String endPoint = null;
    private static String region = null;
    private static String accessKey = null;
    private static String secretKey = null;

    public AmazonS3FileUtils(String bucketName1, String endPoint1, String region1, String accessKey1, String secretKey1) {
        log.info("AmazonS3FileUtils");
        bucketName = bucketName1;
        endPoint = endPoint1;
        region = region1;
        accessKey = accessKey1;
        secretKey = secretKey1;
    }

    private static AmazonS3 getClient() {

        try {
            log.error("getClient start");
            // 新建一个凭证
            log.error("accessKey:"+accessKey);
            log.error("secretKey:"+secretKey);
            AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
            ClientConfiguration clientConfig = new ClientConfiguration();
            clientConfig.setProtocol(Protocol.HTTP);
            AmazonS3 conn = new AmazonS3Client(credentials, clientConfig);
            log.error("conn:"+conn.toString());
            log.error("endPoint:"+endPoint);
            conn.setEndpoint(endPoint);
            //if(!StringUtils.isNull(region)) {
            //}
            return conn;
        } catch (Exception e) {
            log.error("getClient失败", e.getMessage());
            log.error(e.toString());
            return null;
        }
    }

    public static boolean upload(InputStream inputStream, String fileName) {
        AmazonS3 conn = getClient();
        try {
            Bucket bucket = new Bucket(bucketName);
            ObjectMetadata om1 = new ObjectMetadata();
            om1.setContentLength(inputStream.available());
            PutObjectResult pb = conn.putObject(bucket.getName(), fileName, inputStream, om1);
            List<Map<String, Object>> list = list(fileName);
            if (list.size() > 0) {
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("AmazonS3FileUtils失败", e.getMessage());
            return false;
        }
    }

    public static List<Map<String, Object>> list(String fileName) {
        AmazonS3 conn = getClient();
        try {
            List<Bucket> buckets = conn.listBuckets();
            List<Map<String, Object>> files = new ArrayList<Map<String, Object>>();
            // 列出 bucket 的内容
            ObjectListing objects;
            if (fileName != null && !"".equals(fileName)) {
                objects = conn.listObjects(bucketName, fileName);
            } else {
                objects = conn.listObjects(bucketName);
            }
            do {
                for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                    Map map = new HashMap();
                    map.put("fileName", objectSummary.getKey());
                    map.put("fileSize", objectSummary.getSize());
//                    map.put("createTime",StringUtils.fromDate(objectSummary.getLastModified()));
                    files.add(map);
//                    System.out.println(objectSummary.getKey() + "\t" +
//                            objectSummary.getSize());
                }
                objects = conn.listNextBatchOfObjects(objects);
            } while (objects.isTruncated());
            return files;
        } catch (Exception e) {
            log.error("AmazonS3FileUtils失败", e.getMessage());
            return null;
        }
    }


    public static URL download(String fileName) {
        AmazonS3 conn = getClient();
        try {
            Bucket bucket = new Bucket(bucketName);
            // 生成对象的下载 URLs (带签名和不带签名),java仅支持带签名的
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket.getName(), fileName);
            System.out.println(conn.generatePresignedUrl(request));
            return conn.generatePresignedUrl(request);
        } catch (Exception e) {
            log.error("AmazonS3FileUtils失败", e.getMessage());
            return null;
        }
    }

    public static byte[] downloadInputStream(String fileName) {
        try {
            byte[] bytes = downLoadFromUrl(download(fileName).toString());
            return bytes;
        } catch (Exception e) {
            log.error("AmazonS3FileUtils失败", e.getMessage());
            return null;
        }
    }

    public static boolean delete(String fileName) {
        AmazonS3 conn = getClient();
        try {
            Bucket bucket = new Bucket(bucketName);
            conn.deleteObject(bucket.getName(), fileName);
            return true;
        } catch (Exception e) {
            log.error("AmazonS3FileUtils失败", e.getMessage());
            return false;
        }
    }

    public static void downloadFile(String fileName, OutputStream ouputStream) {
        AmazonS3 conn = getClient();
        InputStream input = null;
        try {
            Bucket bucket = new Bucket(bucketName);
            GetObjectRequest gor = new GetObjectRequest(bucket.getName(), fileName);
            S3Object object = conn.getObject(gor);
            input = object.getObjectContent();
            byte[] data = new byte[input.available()];
            System.out.println(data);
            int len = 0;
            while ((len = input.read(data)) != -1) {
                ouputStream.write(data, 0, len);
            }
            System.out.println("下载文件成功");
        } catch (Exception e) {
            log.error("AmazonS3FileUtils失败", e.getMessage());
        } finally {
            if (ouputStream != null) {
                try {
                    ouputStream.close();
                } catch (IOException e) {
                    log.error("AmazonS3FileUtils失败", e.getMessage());
                }
            }
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    log.error("AmazonS3FileUtils失败", e.getMessage());
                }
            }
        }
    }


    /**
     *
     * @param fileName
     * @param response
     * @param oldFileName
     */
    public static void amazonS3Downloading(String fileName, HttpServletResponse response, String oldFileName) {
        AmazonS3 conn = getClient();
        Bucket bucket = new Bucket(bucketName);
        GetObjectRequest gor = new GetObjectRequest(bucket.getName(), fileName);
        S3Object object = conn.getObject(gor);
        if (object != null) {
            System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
            InputStream input = null;
            // FileOutputStream fileOutputStream = null;
            OutputStream out = null;
            byte[] data = null;
            try {
                //获取文件流
                //信息头,相当于新建的名字
                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(oldFileName, "UTF-8"));
                input = object.getObjectContent();
                data = new byte[input.available()];
                int len = 0;
                out = response.getOutputStream();
                //fileOutputStream = new FileOutputStream(targetFilePath);
                while ((len = input.read(data)) != -1) {
                    out.write(data, 0, len);
                }
            } catch (IOException e) {
                log.error("AmazonS3FileUtils失败", e.getMessage());
            } finally {
                //关闭输入输出流
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        log.error("AmazonS3FileUtils失败", e.getMessage());
                    }
                }
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {
                        log.error("AmazonS3FileUtils失败", e.getMessage());
                    }
                }
            }
        }
    }


   

    /**
     * 从网络Url中下载文件
     *
     * @param urlStr
     * @throws IOException
     */
    public static byte[] downLoadFromUrl(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(30 * 1000);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //连接
        conn.connect();
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        byte[] getData = null;
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] d = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(d)) != -1) {
                outputStream.write(d, 0, len);
            }
            outputStream.flush();
            //获取自己数组
            getData = outputStream.toByteArray();
        } catch (Exception e) {
            log.error("AmazonS3FileUtils失败", e.getMessage());
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return getData;
    }


    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

}

这是具体的工具类型,可以直接使用
其实本来和前端商议的也是直接用他们之前的转成base64的格式,但是出了点问题,我发现图片的大小好大啊,转成base64我这边没有办法测试看他转成图片后的样子,所以我只能换成附件下载的样子,直接给前端下载一个图片,

@Override
    public void getLeaderListUrl(HttpServletResponse res,String leaderNo) {
        List<String> leaderListUrlList = cadreLedgerMapper.getLeaderListUrl(leaderNo);
        String filename = "";
        if(null != leaderListUrlList&&leaderListUrlList.size()>0){
            filename = leaderListUrlList.get(0);
            InputStream inputStream = null;
            //这是蛮重要的部分,就是这里穿进去AmazonS3需要的参数,然后这样在调用AmazonS3FileUtils方法的时候才可以直接使用,
            AmazonS3FileUtils amazonS3FileUtils = new AmazonS3FileUtils(bucketName, endPoint, region, accessKey, secretKey);
            byte[] fileData= AmazonS3FileUtils.downloadInputStream(filename);
            try {
                OutputStream out = res.getOutputStream();
                res.setCharacterEncoding("utf8");
                res.setHeader("Content-disposition", "attachment; filename="+filename);
                // 更正Content-Type为jpg对应的MIME类型
                String[] split = filename.split("\\.");
                if(split.length>1){
                    if("png".equals(split[1])){
                        res.setContentType("image/png");
                    }else if("bmp".equals(split[1])){
                        res.setContentType("image/bmp");
                    }else if("gif".equals(split[1])){
                        res.setContentType("image/gif");
                    }else {
                        res.setContentType("image/jpeg");
                    }
                }else {
                    res.setContentType("image/jpeg");
                }
                out.write(fileData);
                out.flush();
                out.close();
            } catch (IOException ioe) {
                log.error(ioe.getMessage(), ioe);
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException ioe) {
                    log.error(ioe.getMessage(), ioe);
                }
            }
        }
    }

nacos配置参数

实话说我本来是想直接写死的,我觉得大概率一个项目就我一个地方再用这个东西了,然后就不大对,我刚好可以实践一下之前学习的nacos配置参数

 	@Value("${amazons3.ceph.bucketName}")
    private String bucketName;

    @Value("${amazons3.ceph.endPoint}")
    private String endPoint;

    @Value("${amazons3.ceph.region}")
    private String region;

    @Value("${amazons3.ceph.accessKey}")
    private String accessKey;

    @Value("${amazons3.ceph.secretKey}")
    private String secretKey;

这是配置上对应的读取nacos的地址
在这里插入图片描述
然后在你的配置文件里面找到对应的nacos,然后登录一下,
在这里插入图片描述

在这里插入图片描述
配置上之后点击发布就可以了,后续如果地址或者账号密码之类的东西改变可以只改配置文件而不影响到代码

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1918795.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

敏捷专家CSM认证培训内容概述(附2024年开班时间表)

敏捷专家CSM认证培训是专为希望在Scrum项目中担任Scrum Master角色的个人而设计的专业培训。CSM认证&#xff0c;全称Certified Scrum Master&#xff0c;是敏捷开发领域中备受认可的证书&#xff0c;由Scrum Alliance颁发。以下是对敏捷专家CSM认证培训的详细介绍&#xff1a;…

solidity实战练习1

//SPDX-License-Identifier:MIT pragma solidity ^0.8.24; contract PiggyBank{constructor()payable{emit Deposit(msg.value);//触发事件1//意味着在部署合约的时候&#xff0c;可以向合约发送以太币&#xff08;不是通过调用函数&#xff0c;而是直接在部署合约时发送&#…

JAVA中的回溯算法解空间树,八皇后问题以及骑士游历问题超详解

1.回溯算法的概念 回溯算法顾名思义就是有回溯的算法 回溯算法实际上一个类似枚举的搜索尝试过程&#xff0c;主要是在搜索尝试过程中寻找问题的解&#xff0c;当发现已不满足求解条件时&#xff0c;就“回溯”返回&#xff0c;尝试别的路径。回溯法是一种选优搜索法&#xff…

Python 神器:wxauto 库——解锁微信自动化的无限可能

&#x1f4dd;个人主页&#x1f339;&#xff1a;誓则盟约 ⏩收录专栏⏪&#xff1a;机器学习 &#x1f921;往期回顾&#x1f921;&#xff1a;“探索机器学习的多面世界&#xff1a;从理论到应用与未来展望” &#x1f339;&#x1f339;期待您的关注 &#x1f339;&#x1f…

短视频矩阵:批量发布的秘密揭秘

在数字化时代&#xff0c;短视频已经成为一种广受欢迎的媒体形式。无论是用于品牌推广、产品营销还是个人创作&#xff0c;短视频都提供了一种直观、生动的方式来吸引观众的注意力。然而&#xff0c;有效地制作、管理和发布短视频对于许多创作者和企业来说是一个挑战。 为此&am…

【Django】报错‘staticfiles‘ is not a registered tag library

错误截图 错误原因总结 在django3.x版本中staticfiles被static替换了&#xff0c;所以这地方换位static即可完美运行 错误解决

旧衣回收小程序开发,提高回收效率,实现创收

随着人们生活水平的提高&#xff0c;对穿衣打扮也越来越重视&#xff0c;衣服更换频率逐渐增高&#xff0c;旧衣回收行业因此产生&#xff0c;并随着市场规模的扩大&#xff0c;拥有了完善的回收产业链&#xff0c; 旧衣回收行业的发展不仅能够让大众获得新的赚钱方式&#xf…

探索创意无限:精彩APP启动页设计案例汇总

启动页是应用启动时出现的过渡页面或动画&#xff0c;旨在提升用户体验、缓解用户焦虑&#xff0c;以及传递品牌或产品的人情味。根据应用性能&#xff0c;其停留时间可能从1秒到3秒不等。启动页同样是应用名片&#xff0c;需要展现品牌的独特个性。运用品牌颜色和 IP 形象能加…

C语言 指针和数组——指针数组的应用:命令行参数

目录 命令行参数 演示命令行参数与main函数形参间的关系 命令行参数  什么是 命令行参数&#xff08; Command Line Arguments &#xff09;&#xff1f;  GUI 界面之前&#xff0c;计算机的操作界面都是字符式的命令行界面 &#xff08; DOS 、 UNIX 、 Linux &…

215.Mit6.S081-实验三-page tables

在本实验室中&#xff0c;您将探索页表并对其进行修改&#xff0c;以简化将数据从用户空间复制到内核空间的函数。 一、实验准备 开始编码之前&#xff0c;请阅读xv6手册的第3章和相关文件&#xff1a; kernel/memlayout.h&#xff0c;它捕获了内存的布局。kernel/vm.c&…

什么是渲染:两种渲染类型、工作原理

如果您是网页设计师或数字艺术家&#xff0c;您可能熟悉渲染过程的概念。这是数字艺术中的重要步骤&#xff0c;帮助您将图形模型转换为最终结果。在本文中&#xff0c;您将了解数字艺术中的渲染是什么、它的工作原理以及它的类型。 一、什么是渲染? 渲染是使用计算机软件对数…

怎么样的主食冻干算好冻干?品质卓越、安全可靠的主食冻干分享

当前主食冻干市场产品质量参差不齐。一些品牌过于追求营养数据的堆砌和利润的增长&#xff0c;却忽视了猫咪健康饮食的基本原则&#xff0c;导致市场上出现了以肉粉冒充鲜肉、修改产品日期等不诚信行为。更令人担忧的是&#xff0c;部分产品未经过严格的第三方质量检测便上市销…

Python实现傅里叶级数可视化工具

Python实现傅里叶级数可视化工具 flyfish 有matlab实现&#xff0c;我没matlab&#xff0c;我有Python&#xff0c;所以我用Python实现。 整个工具的实现代码放在最后,界面使用PyQt5开发 起源 傅里叶级数&#xff08;Fourier Series&#xff09;由法国数学家和物理学家让-巴…

Apache网页优化(企业网站结构部署与优化)

本章结构 一、Apache网页优化 在使用 Apache 作为 Web 服务器的过程中&#xff0c;只有对 Apache 服务器进行适当的优化配置&#xff0c;才能让 Apache 发挥出更好的性能。反过来说&#xff0c;如果 Apache 的配置非常糟糕&#xff0c;Apache可能无法正常为我们服务。因此&…

链接报错undefined reference to + libc++和libstdc++

1 问题现象 subscribe(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) 描述&#xff1a;编译的时候&#xff0c;最后的链接中一直没成功 2 可能原因 2.1 链接时缺失了相关目标文件&#xff08;.o&#x…

Visual Studio 2022 安装及使用

一、下载及安装 VS 官网&#xff1a;Visual Studio: IDE and Code Editor for Software Developers and Teams 下载免费的社区版 得到一个.exe文件 右键安装 选择C开发&#xff0c;并修改安装位置 等待安装 点击启动 二、VS的使用 1.创建项目 打开VS&#xff0c;点击创建新项…

1招搞定maven打包空间不足问题

目录 一、工具应用问题 二 、使用效果 三、使用方法 四、练习手段 一、工具应用问题 使用maven的package功能打包失败&#xff0c;报错“Java heap space”错误。 二 、使用效果 修改IDEA中maven内存使用大小后&#xff0c;打包成功。 三、使用方法 点击菜单“File->Set…

openWrt(4) - uci

uci show 1) uci show - 查看所有配置文件列表 2)查看特定配置文件的详细信息&#xff1a; uci show network 我们以 network 为例 3&#xff09;查看特定配置项的详细信息&#xff1a; uci show network.wan 添加一个新的配置条目&#xff1a;uci add network interface …

Apifox报错404:网络错误,请检查网络,或者稍后再试的解决办法

详细报错如图&#xff1a; 解决办法&#xff1a; 1、检查 请求方法&#xff08;get&#xff0c;post&#xff09;是否正确&#xff0c;请求的URL是否正确&#xff0c;如果不正确&#xff0c;修改后重新发起请求&#xff1b;如果都正确&#xff0c;看2 2、复制curl用postman来…

安防监控/视频汇聚平台EasyCVR设备录像回看请求播放时间和实际时间对不上,是什么原因?

安防监控EasyCVR视频汇聚平台可提供多协议&#xff08;RTSP/RTMP/国标GB28181/GAT1400/海康Ehome/大华/海康/宇视等SDK&#xff09;的设备接入、音视频采集、视频转码、处理、分发等服务&#xff0c;系统具备实时监控、云端录像、回看、告警、平台级联以及多视频流格式分发等视…