部署MinIO

一、安装部署MINIO

1.1 下载

wget https://dl.min.io/server/minio/release/linux-arm64/minio
chmod +x minio
mv minio /usr/local/bin/
# 控制台启动可参考如下命令, 守护进程启动请看下一个代码块
# ./minio server /data /data --console-address ":9001"

1.2 配置

# 配置文件
mkdir -vp /etc/minio/
vim /etc/minio/minio.conf

# 内容BEGIN
# 数据存放目录
MINIO_VOLUMES="/usr/local/minio/data"
# 端口号设置
MINIO_OPTS="--console-address :9001"
# 用户名
MINIO_ROOT_USER="minioadmin"
# 密码
MINIO_ROOT_PASSWORD="minioadmin"
# minio 配置服务固定地址,ip可以更换为自己的ip,不使用下面的设置minio的图片总是默认127.0.0.1。
MINIO_SERVER_URL=http://10.211.55.35:9001
# 内容END

vim /etc/systemd/system/minio.service

# 内容BEGIN
[Unit]
Description=MinIO
Documentation=https://docs.min.io
Wants=network-online.target
After=network-online.target
#minio文件具体位置
AssertFileIsExecutable=/usr/local/bin/minio

[Service]
User=root
Group=root
#创建的配置文件 minio.conf
EnvironmentFile=/etc/minio/minio.conf
ExecStart=/usr/local/bin/minio server $MINIO_OPTS $MINIO_VOLUMES
Restart=always
LimitNOFILE=65536
TimeoutStopSec=infinity
SendSIGKILL=no

[Install]
WantedBy=multi-user.target
# 内容END

# 重新加载 systemd 并启动 minio 服务
systemctl daemon-reload && systemctl start minio

1.3 测试

测试访问: http://10.211.55.35:9001
配置账密: minioadmin/minioadmin



部署MinIO_第1张图片
部署MinIO_第2张图片

可预览,可下载,OK!

二、安装Nginx

# gcc是linux下的编译器, 它可以编译 C、C++、Ada、Object C和Java等语言。
yum -y install gcc
# pcre是一个perl库, 包括perl兼容的正则表达式库, nginx的http模块使用pcre来解析正则表达式。
yum install -y pcre pcre-devel
# zlib库提供了很多种压缩和解压缩方式nginx使用zlib对http包的内容进行gzip, 所以需要安装。
yum install -y zlib zlib-devel
# openssl是web安全通信的基石。
yum install -y openssl openssl-devel

# 下载nginx压缩包
wget http://nginx.org/download/nginx-1.20.2.tar.gz
# 把压缩包解压到/usr/local/src/
tar -zxvf nginx-1.20.2.tar.gz -C /usr/local/src/
# 进入安装目录
cd /usr/local/src/nginx-1.20.2
# 编译安装
./configure && make && make install
# 切换到/usr/local/nginx安装目录
cd /usr/local/nginx
# 启动 nginx 服务
./sbin/nginx
# 查看nginx服务是否启动成功
ps -ef | grep nginx
# 防火墙放行tcp80端口, 或关闭防火墙 systemctl stop firewalld && systemctl disable firewalld
firewall-cmd --add-port=80/tcp
firewall-cmd --add-port=80/tcp --permanent #写入配置文件永久放行

vim ~/.bash_profile
# 内容BEGIN
PATH=/usr/local/nginx/sbin/:$PATH
# 内容END
source ~/.bash_profile

测试访问: http://minio.zhinian.com
部署MinIO_第3张图片

# 常用命令
nginx -s reload            # 重新载入配置文件
nginx -s reopen            # 重启 Nginx
nginx -s stop              # 停止 Nginx

三、配置NG | 转到 MINIO

如果多台MINIO,可做负载。

vim /usr/local/nginx/conf/nginx.conf

# 内容BEGIN
upstream http_minio_back{
	server 10.211.55.35:9001;
    #server ip2:9001;
    #server ip3:9001;
}

server {
	listen       80;
    server_name  localhost;
    location / {
    	proxy_pass http://http_minio_back;

        # 设置反向代理头信息
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        #root   html;
        #index  index.html index.htm;
    }
    location /ws {
        # WebSocket相关设置
        proxy_pass http://http_minio_back;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Origin "";
    }
}
# 内容END

# 重新加载
nginx -s reload

测试访问: http://minio.zhinian.com

四、SpringBoot与MinIO SDK简单集成

4.0 创建MinIO的Access Key


部署MinIO_第4张图片
注:点击Create后会弹出access-key和secret-key,可以下载保存好。

4.1 pom编写


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <groupId>com.zn.opitgroupId>
    <artifactId>minio-demoartifactId>
    <version>1.0.0-SNAPSHOTversion>
    <packaging>jarpackaging>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.7.13version>
        <relativePath/>
    parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.4version>
        dependency>
        
        <dependency>
            <groupId>io.miniogroupId>
            <artifactId>minioartifactId>
            <version>8.2.1version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.5.2version>
        dependency>

        <dependency>
            <groupId>com.imadcn.frameworkgroupId>
            <artifactId>idworkerartifactId>
            <version>1.6.0version>
        dependency>
        
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
		dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                configuration>
            plugin>
        plugins>
    build>
project>

4.2 yaml配置

spring:
  servlet:
    multipart:
      max-file-size: 500MB    # 上传文件总的最大值
      max-request-size: 50MB  # 单个文件的最大值

minio:
  endpoint: http://minio.zhinian.com
  access-key: HAfj5FWeJTPmL9rWDeZp
  secret-key: l82uJsHT10GJXJQtVdRJ8KCHQzbNTHpQnEPSZO0t
  bucketName: zhinian
  folder: demo

4.3 编写代码

4.3.0 主启动类

/**
 * 主启动
 */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class AppMain {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(AppMain.class);
        app.run(args);
    }
}

4.3.1 minio客户端配置

/**
 * MinIo客户端配置
 */
@Getter
@Configuration
public class MinIoClientConfig {

    @Value("${minio.endpoint}")
    private String url;
    @Value("${minio.access-key}")
    private String accessKey;
    @Value("${minio.secret-key}")
    private String secretKey;

    /**
     * 桶名称
     */
    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * 指定文件夹 (每个微服务可以指定一个)
     */
    @Value("${minio.folder}")
    private String folder;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(url)
                .credentials(accessKey, secretKey)
                .build();
    }
}

4.3.2 Service

public interface MinioService {

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 上传结果
     */
    String upload(MultipartFile file);

    /**
     * 预览
     *
     * @param fileName 文件名
     * @return url
     */
    String preview(String fileName);

    /**
     * 文件下载
     *
     * @param fileName 文件名称
     * @param res      response
     */
    void download(String fileName, HttpServletResponse res);
}

4.3.3 ServiceImpl

@Component
@Slf4j
@RequiredArgsConstructor
public class MinioServiceImpl implements MinioService {

    @Resource
    private MinioClient minioClient;

    @Resource
    private MinIoClientConfig minIoClientConfig;

    @Override
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new RuntimeException();
        }
        String fileName = IdWorker.getIdStr() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = minIoClientConfig.getFolder() + File.separator + fileName;
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minIoClientConfig.getBucketName()).object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            log.error("minio upload failed", e);
            return null;
        }
        return objectName;
    }

    @Override
    public String preview(String fileName) {
        // 查看文件地址
        fileName = minIoClientConfig.getFolder() + File.separator + fileName;
        GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder()
                .bucket(minIoClientConfig.getBucketName()).object(fileName).method(Method.GET)
                .build();
        try {
            return minioClient.getPresignedObjectUrl(build);
        } catch (Exception e) {
            log.error("minio preview failed", e);
        }
        return null;
    }


    @Override
    public void download(String fileName, HttpServletResponse res) {
        fileName = minIoClientConfig.getFolder() + File.separator + fileName;
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(minIoClientConfig.getBucketName())
                .object(fileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
                while ((len = response.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("UTF-8");
                // 设置强制下载不打开
                // res.setContentType("application/force-download");
                res.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()) {
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            log.error("minio download failed", e);
        }
    }
}

4.3.4 测试代码

@SpringBootTest(classes = AppMain.class)
public class MinioServiceTest {

    @Resource
    private MinioService minioService;

    @Test
    public void testUpload() {
        File file = new File("/Users/zhinian/IdeaProjects/minio-demo/src/test/resources/images/jenkins.png");
        FileItem fileItem = this.getMultipartFile(file, "jenkins.png");
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        String upload = minioService.upload(multipartFile);
        System.out.println(upload);
    }

}


部署MinIO_第5张图片
测试上传预览下载

### 上传
POST http://127.0.0.1:8888/file/upload
Content-Type: multipart/form-data; boundary=WebAppBoundary

--WebAppBoundary
Content-Disposition: form-data; name="file"; filename="credentials.json"

< /Users/zhinian/IdeaProjects/minio-demo/src/test/resources/json/credentials.json
--WebAppBoundary--

### 预览
GET http://127.0.0.1:8888/file/preview/1747639493380743170.json
Accept: application/json

### 下载
GET http://127.0.0.1:8888/file/download/1747639493380743170.json

>> /Users/zhinian/IdeaProjects/minio-demo/src/test/resources/json/credentials-copy.json

代码仓库: minio-demo


参考:
https://blog.csdn.net/qq_38403590/article/details/128241787
https://www.nhooo.com/note/qagbfy.html
https://blog.csdn.net/Mr_Richard/article/details/132303927

需要注意的是,minio服务端口默认为9000,与我们使用的web控制台端口是不一样的。本片中,选择下图中的S3 API port而非web控制台Console

部署MinIO_第6张图片

The difference between the request time and the server's time is too large.

# 时间同步
# 1.设置系统时区为上海时区
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
# 2.安装nptdate
yum install -y ntpdate
# 3.同步网络时间
ntpdate us.pool.ntp.org
io.minio.errors.ErrorResponseException: Access Denied.

部署MinIO_第7张图片
https://blog.csdn.net/Mou_O/article/details/133991854

你可能感兴趣的:(macos)