0


黑马头条微服务学习day02-app端文章查看,静态化freemarker,分布式文件系统MinlO

文章目录

app端文章列表

需求分析

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

实现思路

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

实现步骤

在这里插入图片描述
ArticleHomeDto

packagecom.heima.model.article.dtos;importlombok.Data;importjava.util.Date;@DatapublicclassArticleHomeDto{// 最大时间Date maxBehotTime;// 最小时间Date minBehotTime;// 分页sizeInteger size;// 频道IDString tag;}

导入heima-leadnews-article微服务

注意:需要在heima-leadnews-service的pom文件夹中添加子模块信息,如下:

<modules><module>heima-leadnews-user</module><module>heima-leadnews-article</module></modules>

在idea中的maven中更新一下,如果工程还是灰色的,需要在重新添加文章微服务的pom文件,操作步骤如下:

需要在nacos中添加对应的配置

spring:datasource:driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/leadnews_article?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTCusername: root
    password: root
# 设置Mapper接口所对应的XML文件位置,如果你在Mapper接口中有自定义方法,需要进行该配置mybatis-plus:mapper-locations: classpath*:mapper/*.xml# 设置别名包扫描路径,通过该属性可以给包中的类注册别名type-aliases-package: com.heima.model.article.pojos

定义接口

packagecom.heima.article.controller.v1;importcom.heima.model.article.dtos.ArticleHomeDto;importcom.heima.model.common.dtos.ResponseResult;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestBody;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/api/v1/article")publicclassArticleHomeController{@PostMapping("/load")publicResponseResultload(@RequestBodyArticleHomeDto dto){returnnull;}@PostMapping("/loadmore")publicResponseResultloadMore(@RequestBodyArticleHomeDto dto){returnnull;}@PostMapping("/loadnew")publicResponseResultloadNew(@RequestBodyArticleHomeDto dto){returnnull;}}
编写mapper文件
packagecom.heima.article.mapper;importcom.baomidou.mybatisplus.core.mapper.BaseMapper;importcom.heima.model.article.dtos.ArticleHomeDto;importcom.heima.model.article.pojos.ApArticle;importorg.apache.ibatis.annotations.Mapper;importorg.apache.ibatis.annotations.Param;importjava.util.List;@MapperpublicinterfaceApArticleMapperextendsBaseMapper<ApArticle>{publicList<ApArticle>loadArticleList(@Param("dto")ArticleHomeDto dto,@Param("type")Short type);}

对应的映射文件

在resources中新建mapper/ApArticleMapper.xml 如下配置:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.heima.article.mapper.ApArticleMapper"><resultMapid="resultMap"type="com.heima.model.article.pojos.ApArticle"><idcolumn="id"property="id"/><resultcolumn="title"property="title"/><resultcolumn="author_id"property="authorId"/><resultcolumn="author_name"property="authorName"/><resultcolumn="channel_id"property="channelId"/><resultcolumn="channel_name"property="channelName"/><resultcolumn="layout"property="layout"/><resultcolumn="flag"property="flag"/><resultcolumn="images"property="images"/><resultcolumn="labels"property="labels"/><resultcolumn="likes"property="likes"/><resultcolumn="collection"property="collection"/><resultcolumn="comment"property="comment"/><resultcolumn="views"property="views"/><resultcolumn="province_id"property="provinceId"/><resultcolumn="city_id"property="cityId"/><resultcolumn="county_id"property="countyId"/><resultcolumn="created_time"property="createdTime"/><resultcolumn="publish_time"property="publishTime"/><resultcolumn="sync_status"property="syncStatus"/><resultcolumn="static_url"property="staticUrl"/></resultMap><selectid="loadArticleList"resultMap="resultMap">
        SELECT
        aa.*
        FROM
        `ap_article` aa
        LEFT JOIN ap_article_config aac ON aa.id = aac.article_id
        <where>
            and aac.is_delete != 1
            and aac.is_down != 1
            <!-- loadmore --><iftest="type != null and type == 1">
                and aa.publish_time <![CDATA[<]]> #{dto.minBehotTime}
            </if><iftest="type != null and type == 2">
                and aa.publish_time <![CDATA[>]]> #{dto.maxBehotTime}
            </if><iftest="dto.tag != '__all__'">
                and aa.channel_id = #{dto.tag}
            </if></where>
        order by aa.publish_time desc
        limit #{dto.size}
    </select></mapper>

编写业务层代码

packagecom.heima.article.service;importcom.baomidou.mybatisplus.extension.service.IService;importcom.heima.model.article.dtos.ArticleHomeDto;importcom.heima.model.article.pojos.ApArticle;importcom.heima.model.common.dtos.ResponseResult;importjava.io.IOException;publicinterfaceApArticleServiceextendsIService<ApArticle>{/**
     * 根据参数加载文章列表
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */ResponseResultload(Short loadtype,ArticleHomeDto dto);}

实现类:

packagecom.heima.article.service.impl;importcom.baomidou.mybatisplus.extension.service.impl.ServiceImpl;importcom.heima.article.mapper.ApArticleMapper;importcom.heima.article.service.ApArticleService;importcom.heima.common.constants.ArticleConstants;importcom.heima.model.article.dtos.ArticleHomeDto;importcom.heima.model.article.pojos.ApArticle;importcom.heima.model.common.dtos.ResponseResult;importlombok.extern.slf4j.Slf4j;importorg.apache.commons.lang3.StringUtils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Transactional;importjava.util.Date;importjava.util.List;@Service@Transactional@Slf4jpublicclassApArticleServiceImplextendsServiceImpl<ApArticleMapper,ApArticle>implementsApArticleService{// 单页最大加载的数字privatefinalstaticshortMAX_PAGE_SIZE=50;@AutowiredprivateApArticleMapper apArticleMapper;/**
     * 根据参数加载文章列表
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */@OverridepublicResponseResultload(Short loadtype,ArticleHomeDto dto){//1.校验参数Integer size = dto.getSize();if(size ==null|| size ==0){
            size =10;}
        size =Math.min(size,MAX_PAGE_SIZE);
        dto.setSize(size);//类型参数检验if(!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)&&!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            loadtype =ArticleConstants.LOADTYPE_LOAD_MORE;}//文章频道校验if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);}//时间校验if(dto.getMaxBehotTime()==null) dto.setMaxBehotTime(newDate());if(dto.getMinBehotTime()==null) dto.setMinBehotTime(newDate());//2.查询数据List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);//3.结果封装ResponseResult responseResult =ResponseResult.okResult(apArticles);return responseResult;}}

定义常量类

packagecom.heima.common.constants;publicclassArticleConstants{publicstaticfinalShortLOADTYPE_LOAD_MORE=1;publicstaticfinalShortLOADTYPE_LOAD_NEW=2;publicstaticfinalStringDEFAULT_TAG="__all__";}
编写控制器代码
packagecom.heima.article.controller.v1;importcom.heima.article.service.ApArticleService;importcom.heima.common.constants.ArticleConstants;importcom.heima.model.article.dtos.ArticleHomeDto;importcom.heima.model.common.dtos.ResponseResult;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestBody;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/api/v1/article")publicclassArticleHomeController{@AutowiredprivateApArticleService apArticleService;@PostMapping("/load")publicResponseResultload(@RequestBodyArticleHomeDto dto){return apArticleService.load(ArticleConstants.LOADTYPE_LOAD_MORE,dto);}@PostMapping("/loadmore")publicResponseResultloadMore(@RequestBodyArticleHomeDto dto){return apArticleService.load(ArticleConstants.LOADTYPE_LOAD_MORE,dto);}@PostMapping("/loadnew")publicResponseResultloadNew(@RequestBodyArticleHomeDto dto){return apArticleService.load(ArticleConstants.LOADTYPE_LOAD_NEW,dto);}}

页面展示

在这里插入图片描述

文章详情

实现思路

在这里插入图片描述

在这里插入图片描述

Freemarker

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
创建一个freemarker-demo 的测试工程专门用于freemarker的功能测试与模板的测试。

pom.xml如下

<?xml version="1.0" encoding="UTF-8"?><projectxmlns="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"><parent><artifactId>heima-leadnews-test</artifactId><groupId>com.heima</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>freemarker-demo</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- apache 对 java io 的封装工具库 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-io</artifactId><version>1.3.2</version></dependency></dependencies></project>

在freemarker的测试工程下创建模型类型用于测试

packagecom.heima.freemarker.entity;importlombok.Data;importjava.util.Date;@DatapublicclassStudent{privateString name;//姓名privateint age;//年龄privateDate birthday;//生日privateFloat money;//钱包}

在resources下创建templates,此目录为freemarker的默认模板存放目录。

在templates下创建模板文件 01-basic.ftl ,模板中的插值表达式最终会被freemarker替换成具体的数据。

<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>Hello World!</title></head><body><b>普通文本 String 展示:</b><br><br>
Hello ${name} <br><hr><b>对象Student中的数据展示:</b><br/>
姓名:${stu.name}<br/>
年龄:${stu.age}
<hr></body></html>

创建Controller类,向Map中添加name,最后返回模板文件。

packagecom.xuecheng.test.freemarker.controller;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.client.RestTemplate;importjava.util.Map;@ControllerpublicclassHelloController{@GetMapping("/basic")publicStringtest(Model model){//1.纯文本形式的参数
        model.addAttribute("name","freemarker");//2.实体类相关的参数Student student =newStudent();
        student.setName("小明");
        student.setAge(18);
        model.addAttribute("stu", student);return"01-basic";}}

01-basic.ftl,使用插值表达式填充数据

<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>Hello World!</title></head><body><b>普通文本 String 展示:</b><br><br>
Hello ${name} <br><hr><b>对象Student中的数据展示:</b><br/>
姓名:${stu.name}<br/>
年龄:${stu.age}
<hr></body></html>

创建启动类

packagecom.heima.freemarker;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublicclassFreemarkerDemotApplication{publicstaticvoidmain(String[] args){SpringApplication.run(FreemarkerDemotApplication.class,args);}}

在这里插入图片描述

minIO

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
我们提供的镜像中已经有minio的环境

我们可以使用docker进行环境部署和启动

docker run -p 9000:9000-p 9001:9001--name minio -d --restart=always \ 
  -e "MINIO_ROOT_USER=minio" \
  -e "MINIO_ROOT_PASSWORD=minio123" \
  -v /home/data:/data \
  -v /home/config:/root/.minio \
  minio/minio server /data --console-address ":9001"

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
导入pom依赖

创建minio-demo,对应pom如下

<?xml version="1.0" encoding="UTF-8"?><projectxmlns="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"><parent><artifactId>heima-leadnews-test</artifactId><groupId>com.heima</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>minio-demo</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>7.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency></dependencies></project>

引导类:

packagecom.heima.minio;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublicclassMinIOApplication{publicstaticvoidmain(String[] args){SpringApplication.run(MinIOApplication.class,args);}}

创建测试类,上传html文件

packagecom.heima.minio.test;importio.minio.MinioClient;importio.minio.PutObjectArgs;importjava.io.FileInputStream;publicclassMinIOTest{publicstaticvoidmain(String[] args){FileInputStream fileInputStream =null;try{

            fileInputStream =newFileInputStream("D:\\list.html");;//1.创建minio链接客户端MinioClient minioClient =MinioClient.builder().credentials("minio","minio123").endpoint("http://192.168.200.130:9000").build();//2.上传PutObjectArgs putObjectArgs =PutObjectArgs.builder().object("list.html")//文件名.contentType("text/html")//文件类型.bucket("leadnews")//桶名词  与minio创建的名词一致.stream(fileInputStream, fileInputStream.available(),-1)//文件流.build();
            minioClient.putObject(putObjectArgs);System.out.println("http://192.168.200.130:9000/leadnews/ak47.jpg");}catch(Exception ex){
            ex.printStackTrace();}}}

在这里插入图片描述
在这里插入图片描述
创建模块heima-file-starter

导入依赖

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>7.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency></dependencies>

配置类

MinIOConfigProperties

packagecom.heima.file.config;importlombok.Data;importorg.springframework.boot.context.properties.ConfigurationProperties;importjava.io.Serializable;@Data@ConfigurationProperties(prefix ="minio")// 文件上传 配置前缀file.osspublicclassMinIOConfigPropertiesimplementsSerializable{privateString accessKey;privateString secretKey;privateString bucket;privateString endpoint;privateString readPath;}

MinIOConfig

packagecom.heima.file.config;importcom.heima.file.service.FileStorageService;importio.minio.MinioClient;importlombok.Data;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.autoconfigure.condition.ConditionalOnClass;importorg.springframework.boot.context.properties.EnableConfigurationProperties;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;@Data@Configuration@EnableConfigurationProperties({MinIOConfigProperties.class})//当引入FileStorageService接口时@ConditionalOnClass(FileStorageService.class)publicclassMinIOConfig{@AutowiredprivateMinIOConfigProperties minIOConfigProperties;@BeanpublicMinioClientbuildMinioClient(){returnMinioClient.builder().credentials(minIOConfigProperties.getAccessKey(), minIOConfigProperties.getSecretKey()).endpoint(minIOConfigProperties.getEndpoint()).build();}}

封装操作minIO类

FileStorageService

packagecom.heima.file.service;importjava.io.InputStream;/**
 * @author itheima
 */publicinterfaceFileStorageService{/**
     *  上传图片文件
     * @param prefix  文件前缀
     * @param filename  文件名
     * @param inputStream 文件流
     * @return  文件全路径
     */publicStringuploadImgFile(String prefix,String filename,InputStream inputStream);/**
     *  上传html文件
     * @param prefix  文件前缀
     * @param filename   文件名
     * @param inputStream  文件流
     * @return  文件全路径
     */publicStringuploadHtmlFile(String prefix,String filename,InputStream inputStream);/**
     * 删除文件
     * @param pathUrl  文件全路径
     */publicvoiddelete(String pathUrl);/**
     * 下载文件
     * @param pathUrl  文件全路径
     * @return
     *
     */publicbyte[]downLoadFile(String pathUrl);}

MinIOFileStorageService

packagecom.heima.file.service.impl;importcom.heima.file.config.MinIOConfig;importcom.heima.file.config.MinIOConfigProperties;importcom.heima.file.service.FileStorageService;importio.minio.GetObjectArgs;importio.minio.MinioClient;importio.minio.PutObjectArgs;importio.minio.RemoveObjectArgs;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.context.properties.EnableConfigurationProperties;importorg.springframework.context.annotation.Import;importorg.springframework.util.StringUtils;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.text.SimpleDateFormat;importjava.util.Date;@Slf4j@EnableConfigurationProperties(MinIOConfigProperties.class)@Import(MinIOConfig.class)publicclassMinIOFileStorageServiceimplementsFileStorageService{@AutowiredprivateMinioClient minioClient;@AutowiredprivateMinIOConfigProperties minIOConfigProperties;privatefinalstaticString separator ="/";/**
     * @param dirPath
     * @param filename  yyyy/mm/dd/file.jpg
     * @return
     */publicStringbuilderFilePath(String dirPath,String filename){StringBuilder stringBuilder =newStringBuilder(50);if(!StringUtils.isEmpty(dirPath)){
            stringBuilder.append(dirPath).append(separator);}SimpleDateFormat sdf =newSimpleDateFormat("yyyy/MM/dd");String todayStr = sdf.format(newDate());
        stringBuilder.append(todayStr).append(separator);
        stringBuilder.append(filename);return stringBuilder.toString();}/**
     *  上传图片文件
     * @param prefix  文件前缀
     * @param filename  文件名
     * @param inputStream 文件流
     * @return  文件全路径
     */@OverridepublicStringuploadImgFile(String prefix,String filename,InputStream inputStream){String filePath =builderFilePath(prefix, filename);try{PutObjectArgs putObjectArgs =PutObjectArgs.builder().object(filePath).contentType("image/jpg").bucket(minIOConfigProperties.getBucket()).stream(inputStream,inputStream.available(),-1).build();
            minioClient.putObject(putObjectArgs);StringBuilder urlPath =newStringBuilder(minIOConfigProperties.getReadPath());
            urlPath.append(separator+minIOConfigProperties.getBucket());
            urlPath.append(separator);
            urlPath.append(filePath);return urlPath.toString();}catch(Exception ex){
            log.error("minio put file error.",ex);thrownewRuntimeException("上传文件失败");}}/**
     *  上传html文件
     * @param prefix  文件前缀
     * @param filename   文件名
     * @param inputStream  文件流
     * @return  文件全路径
     */@OverridepublicStringuploadHtmlFile(String prefix,String filename,InputStream inputStream){String filePath =builderFilePath(prefix, filename);try{PutObjectArgs putObjectArgs =PutObjectArgs.builder().object(filePath).contentType("text/html").bucket(minIOConfigProperties.getBucket()).stream(inputStream,inputStream.available(),-1).build();
            minioClient.putObject(putObjectArgs);StringBuilder urlPath =newStringBuilder(minIOConfigProperties.getReadPath());
            urlPath.append(separator+minIOConfigProperties.getBucket());
            urlPath.append(separator);
            urlPath.append(filePath);return urlPath.toString();}catch(Exception ex){
            log.error("minio put file error.",ex);
            ex.printStackTrace();thrownewRuntimeException("上传文件失败");}}/**
     * 删除文件
     * @param pathUrl  文件全路径
     */@Overridepublicvoiddelete(String pathUrl){String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");int index = key.indexOf(separator);String bucket = key.substring(0,index);String filePath = key.substring(index+1);// 删除ObjectsRemoveObjectArgs removeObjectArgs =RemoveObjectArgs.builder().bucket(bucket).object(filePath).build();try{
            minioClient.removeObject(removeObjectArgs);}catch(Exception e){
            log.error("minio remove file error.  pathUrl:{}",pathUrl);
            e.printStackTrace();}}/**
     * 下载文件
     * @param pathUrl  文件全路径
     * @return  文件流
     *
     */@Overridepublicbyte[]downLoadFile(String pathUrl){String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");int index = key.indexOf(separator);String bucket = key.substring(0,index);String filePath = key.substring(index+1);InputStream inputStream =null;try{
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(minIOConfigProperties.getBucket()).object(filePath).build());}catch(Exception e){
            log.error("minio down file error.  pathUrl:{}",pathUrl);
            e.printStackTrace();}ByteArrayOutputStream byteArrayOutputStream =newByteArrayOutputStream();byte[] buff =newbyte[100];int rc =0;while(true){try{if(!((rc = inputStream.read(buff,0,100))>0))break;}catch(IOException e){
                e.printStackTrace();}
            byteArrayOutputStream.write(buff,0, rc);}return byteArrayOutputStream.toByteArray();}}

对外加入自动配置

在resources中新建

META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.heima.file.service.impl.MinIOFileStorageService

其他微服务使用

第一,导入heima-file-starter的依赖

第二,在微服务中添加minio所需要的配置

minio:accessKey: minio
  secretKey: minio123
  bucket: leadnews
  endpoint: http://192.168.200.130:9000readPath: http://192.168.200.130:9000

第三,在对应使用的业务类中注入FileStorageService,样例如下:

packagecom.heima.minio.test;importcom.heima.file.service.FileStorageService;importcom.heima.minio.MinioApplication;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringRunner;importjava.io.FileInputStream;importjava.io.FileNotFoundException;@SpringBootTest(classes =MinioApplication.class)@RunWith(SpringRunner.class)publicclassMinioTest{@AutowiredprivateFileStorageService fileStorageService;@TestpublicvoidtestUpdateImgFile(){try{FileInputStream fileInputStream =newFileInputStream("E:\\tmp\\ak47.jpg");String filePath = fileStorageService.uploadImgFile("","ak47.jpg", fileInputStream);System.out.println(filePath);}catch(FileNotFoundException e){
            e.printStackTrace();}}}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在文章微服务中导入依赖

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency><dependency><groupId>com.heima</groupId><artifactId>heima-file-starter</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies>

新建ApArticleContentMapper

packagecom.heima.article.mapper;importcom.baomidou.mybatisplus.core.mapper.BaseMapper;importcom.heima.model.article.pojos.ApArticleContent;importorg.apache.ibatis.annotations.Mapper;@MapperpublicinterfaceApArticleContentMapperextendsBaseMapper<ApArticleContent>{}

6.在artile微服务中新增测试类(后期新增文章的时候创建详情静态页,目前暂时手动生成)

packagecom.heima.article.test;importcom.alibaba.fastjson.JSONArray;importcom.baomidou.mybatisplus.core.toolkit.Wrappers;importcom.heima.article.ArticleApplication;importcom.heima.article.mapper.ApArticleContentMapper;importcom.heima.article.mapper.ApArticleMapper;importcom.heima.file.service.FileStorageService;importcom.heima.model.article.pojos.ApArticle;importcom.heima.model.article.pojos.ApArticleContent;importfreemarker.template.Configuration;importfreemarker.template.Template;importorg.apache.commons.lang3.StringUtils;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringRunner;importjava.io.ByteArrayInputStream;importjava.io.InputStream;importjava.io.StringWriter;importjava.util.HashMap;importjava.util.Map;@SpringBootTest(classes =ArticleApplication.class)@RunWith(SpringRunner.class)publicclassArticleFreemarkerTest{@AutowiredprivateConfiguration configuration;@AutowiredprivateFileStorageService fileStorageService;@AutowiredprivateApArticleMapper apArticleMapper;@AutowiredprivateApArticleContentMapper apArticleContentMapper;@TestpublicvoidcreateStaticUrlTest()throwsException{//1.获取文章内容ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,1390536764510310401L));if(apArticleContent !=null&&StringUtils.isNotBlank(apArticleContent.getContent())){//2.文章内容通过freemarker生成html文件StringWriter out =newStringWriter();Template template = configuration.getTemplate("article.ftl");Map<String,Object> params =newHashMap<>();
            params.put("content",JSONArray.parseArray(apArticleContent.getContent()));

            template.process(params, out);InputStream is =newByteArrayInputStream(out.toString().getBytes());//3.把html文件上传到minio中String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId()+".html", is);//4.修改ap_article表,保存static_url字段ApArticle article =newApArticle();
            article.setId(apArticleContent.getArticleId());
            article.setStaticUrl(path);
            apArticleMapper.updateById(article);}}}
标签: 微服务 学习 架构

本文转载自: https://blog.csdn.net/qq_48642405/article/details/140405516
版权归原作者 Jimmy Ding 所有, 如有侵权,请联系我们删除。

“黑马头条微服务学习day02-app端文章查看,静态化freemarker,分布式文件系统MinlO”的评论:

还没有评论