MinIO installation configuration access and SpringBoot integration MinIO

MinIO

1. MinIO installation

Minio is an open source object storage service written based on Golang, which stores unstructured data, such as pictures, videos, music, etc.

What is object storage?

Object Storage Service (OSS) is a massive, secure, low-cost, and highly reliable cloud storage service, suitable for storing any type of file. Elastic expansion of capacity and processing power, multiple storage types to choose from, and comprehensive optimization of storage costs.

For small and medium-sized enterprises, if they do not choose to store on the cloud, then Minio is a good choice. Although the sparrow is small, it has all the internal organs

1.1 Installation on CentOS7

1. Download MinIO

a, enter the /usr/local directory

cd /usr/local

b. Create a minio folder under usr/local, create bin and data directories in the minio file, and copy the downloaded minio file to the bin directory

2. Give it executable permissions

chmod +x bin/minio

3. Set account password

export MINIO_ROOT_USER=minioadmin
export MINIO_ROOT_PASSWORD=minioadmin

4. Add minio as a Linux service

Create a new minio.service file in /etc/systemd/system and write the following configuration file

[Unit]
Description=Minio
Wants=network-online.target
After=network-online.target
AssertFileIsExecutable=/usr/local/minio/bin/minio

[Service]
WorkingDirectory=/usr/local/minio/
PermissionsStartOnly=true
ExecStart=/usr/local/minio/bin/minio server /usr/local/minio/data
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

In this way, you can use systemctl to start and stop minio

systemctl start minio   # 启动
systemctl stop minio    # 停止

Visit [http://192.168.128.128:9000] after MinIO Server is successfully started, and you will see an interface similar to the following:

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-nPrSrkje-1681122454536)(assets/image-20220511122601979.png)]

Enter the user name/password minioadmin/minioadminto enter the web management system:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-PF2MPhO6-1681122454538)(assets/image-20220511144126982.png)]

When it was first opened, there was no bucket. You can create a bucket manually or through java code.

The default permission of the created bucket is private and cannot be accessed from the outside. You can modify the properties of the bucket, click manage, find Access Policy, and modify the permission to public.

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-hr2CdUe3-1681122454538)(assets/image-20220511144607329.png)]

1.2 Install on Windows

a, Initialize the directory

Create a new folder, put the minio.exe file (the file is linked at the beginning of the article) into the file, and create a data folder under this folder to store data

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-hrTwd6Ex-1681122454539) (C:\Users\lps\AppData\Roaming\Typora\typora-user-images\ image-20230410162230387.png)]

b, set the administrator account and password

set MINIO_ACCESS_KEY=minioadmin
set MINIO_SECRET_KEY=minioadmin

c, start minio

minio.exe server D:\software\minio\data --console-address ":9001" --address ":9000"

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-xZ7axxK5-1681122454539) (C:\Users\lps\AppData\Roaming\Typora\typora-user-images\ image-20230410162504312.png)]

d, configure minio permanent access

mc.exe config host add minio http://192.168.0.103:9000 minioadmin minioadmin

f, access port settings access permissions

insert image description here

set to public

2. springboot integrates MinIO

1. Introduce dependencies

 <dependency>
     <groupId>com.squareup.okhttp3</groupId>
     <artifactId>okhttp</artifactId>
     <version>4.8.1</version> <!-- minio 依赖于 okhttp 且版本较高。注意,spring-boot-dependencies 中的不够高 -->
</dependency>
<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>8.3.9</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>
        

2. Relevant configuration (yaml and properties are selected according to your own situation)

server:
  port: 8080
spring:
  servlet:
    multipart:
      max-file-size: 200MB  #设置单个文件的大小  因为springboot内置tomact的的文件传输默认为10MB
      max-request-size: 500MB   #设置单次请求的文件总大小
      enabled: true    #千万注意要设置该参数,否则不生效
# minio 文件存储配置信息
minio:
  endpoint: http://127.0.0.1:9000
  accesskey: minioadmin
  secretKey: minioadmin
  
 ==========================properties===================
spring.servlet.multipart.max-file-size=200MB
spring.servlet.multipart.max-request-size=500MB
spring.servlet.multipart.enabled=true

minio.endpoint:http://127.0.0.1:9000
minio.accesskey:minioadmin
minio.secretkey:minioadmin

3.minio configuration class and configuration properties

@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioProp {
    
    
    private String endpoint;
    private String accesskey;
    private String secretKey;
}
=============================================
@Configuration
@EnableConfigurationProperties(MinioProp.class)
public class MinioConfig {
    
    
    @Autowired
    private MinioProp minioProp;
    @Bean
    public MinioClient minioClient() throws Exception {
    
    
       return MinioClient.builder().endpoint(minioProp.getEndpoint())
               .credentials(minioProp.getAccesskey(), minioProp.getSecretKey()).build();
    }
}

4. Write a simple file upload tool class

@Slf4j
@Component
public class MinioUtils {
    
    

    @Autowired
    private MinioClient client;
    @Autowired
    private MinioProp minioProp;
   
    /**
     * 创建bucket
     */
    public void createBucket(String bucketName) {
    
    
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
        try {
    
    
            if (client.bucketExists(bucketExistsArgs))
                return;
            client.makeBucket(makeBucketArgs);
        } catch (Exception e) {
    
    
            log.error("创建桶失败:{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * @param file       文件
     * @param bucketName 存储桶
     * @return
     */
    public JSONObject uploadFile(MultipartFile file, String bucketName) throws Exception {
    
    
        JSONObject res = new JSONObject();
        res.put("code", 0);
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
    
    
            res.put("msg", "上传文件不能为空");
            return res;
        }
        // 判断存储桶是否存在
        createBucket(bucketName);
        // 文件名
        String originalFilename = file.getOriginalFilename();
        // 新的文件名 = 存储桶名称_时间戳.后缀名
        String fileName = bucketName + "_" + System.currentTimeMillis() +                              									originalFilename.substring(originalFilename.lastIndexOf("."));
        // 开始上传
        InputStream inputStream = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder().bucket(bucketName).object(fileName)
                .stream(inputStream,inputStream.available(),-1).build();
        client.putObject(args);
        res.put("code", 1);
        res.put("msg", minioProp.getEndpoint() + "/" + bucketName + "/" + fileName);
        return res;
    }
}

5. Controller layer test

@RestController
public class MinioController {
    
    

    @Autowired
    private MinioUtils minioUtils;

    @PostMapping("/uploadimg")
    public String uploadimg(MultipartFile file ) {
    
    
        JSONObject res = null;
        try {
    
    
            res = minioUtils.uploadFile(file, "test");
        } catch (Exception e) {
    
    
            e.printStackTrace();
            res.put("code", 0);
            res.put("msg", "上传失败");
        }
        return res.toJSONString();
    }
}

6. Page writing, uploading videos and pictures (element ui)

  <el-upload
                  
    action="api/uploadimg"
    :show-file-list="false"
    :on-success="handleAvatarSuccess">
      <img v-if="imageUrl" :src="imageUrl" >
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

   handleAvatarSuccess(res, file) {
        debugger;
        this.imageUrl =res.msg+'';
      },

Note: After the upload is complete, the returned url address is: http://service ip:port/bucket name/file name

ccess=“handleAvatarSuccess”>


handleAvatarSuccess(res, file) {
debugger;
this.imageUrl =res.msg+‘’;
},


注意:上传完成后,返回的url地址为:http://服务ip:端口/桶名称/文件名

![在这里插入图片描述](https://img-blog.csdnimg.cn/d29128502c034009822a8753bbf85298.png)

Guess you like

Origin blog.csdn.net/lps12345666/article/details/130066718