乐优商城day07(fastDFS模块)

所有代码发布在 [https://github.com/hades0525/leyou]

 

Day07

2019124

21:47

品牌管理

    1. 查询和搜索
      1. BrandMapper
      2. Brandcontroller

写controller之前需要知道4个值

 

 

- 请求方式:

- 请求路径:

- 请求参数:

 - 响应结果:

 

publicResponseEntity<PageResult<Brand>>queryBrandByPage(

@RequestParam(value="page",defaultValue="1")Integerpage,

@RequestParam(value="rows",defaultValue="5")Integerrows,

@RequestParam(value="sortBy",required=false)StringsortBy,

@RequestParam(value="desc",defaultValue="false")booleandesc,

@RequestParam(value="key",required=false)Stringkey

){

returnResponseEntity.ok(brandService.queryBrandByPage(page,rows,sortBy,desc,key));

}

    
    1. 分页类(放在common包里,通用)

classPageResult<T>{

privateLongtotal;//总条数

privateIntegertotalPage;//总页数

privateList<T>items;//当前页数据

publicPageResult(){}

 

publicPageResult(Longtotal,List<T>items){

this.total=total;

this.items=items;

}

 

publicPageResult(Longtotal,List<T>items,IntegertotalPage){

this.total=total;

this.items=items;

this.totalPage=totalPage;

}

    1. 如果有自定义的构造函数(不是空参或全参),就不能再使用lombok的构造函数注解,会报错
    2. BrandService  实现分页效果

PageResult<Brand> queryBrandByPage(Integer page, Integer rows, String sortBy, boolean desc, String key) {

        //分页

        PageHelper.startPage(page,rows);

        /*

        * where 'name' like '%x%' or letter == 'x'

        * order by id desc

        * */

        //过滤

        Example example = new Example(Brand.class);

        if(StringUtils.isNotBlank(key)){

           example.createCriteria().orLike("name","%"+key+"%")

           .orEqualTo("letter",key.toUpperCase());

        }

        //排序

        if(StringUtils.isNotBlank(sortBy)){

      //查询语句 严格按照sql语句。desc前面必须有空格

            String oderByClause = sortBy+(desc ? " desc":" asc");

            example.setOrderByClause(oderByClause);

        }

 

        //查询

        List<Brand> list = brandMapper.selectByExample(example);

        if(CollectionUtils.isEmpty(list)){

            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);

        }

        //解析分页结果,自动封装总页数

        PageInfo<Brand> info = new PageInfo<>(list);

        return new PageResult<>(info.getTotal(),list);

    }

    • pagehelper分页不生效,maven依赖库出错误,把父项目的依赖版本管理修改
    • 前端页面

watch:{

          key(){

            this.pagination.page = 1;

          },

        pagination:{

            deep:true,

            handler(){

              this.loadBrands();

            }

        }

      },

 

      methods:{

          loadBrands(){

            this.loading = true;

            this.$http.get("/item/brand/page",{

              params:{

                page:this.pagination.page,//当前页

                rows:this.pagination.rowsPerPage,//每页大小

                sortBy:this.pagination.sortBy,//排序字段

                desc:this.pagination.descending,//是否降序

                key:this.key//搜索条件

              }

            }).then(resp => {

              this.brands = resp.data.items;

              this.totalBrands = resp.data.total;

              this.loading = false;

            })

          }

      }

    1. 新增
      1. 新增品牌分类级联选择:cascader.vue(自定义的)
        1. brandcontroller 新增品牌时,传入的参数(brand对象,分类的ids)

@PostMapping

publicResponseEntity<Void>saveBrand(Brandbrand,@RequestParam("cids")List<Long>cids){

brandService.saveBrand(brand,cids);

returnResponseEntity.status(HttpStatus.CREATED).build();

}

    1. brandservice 新增品牌的时,保存品牌的分类

  @Transactional

    public void saveBrand(Brand brand, List<Long> cids) {

        //新增品牌

        brand.setId(null);

        int count = brandMapper.insert(brand);

        if(count !=1 ){

            //新增失败

            throw new LyException(ExceptionEnum.BRAND_SAVE_ERROR);

        }

        for (Long cid : cids) {

           count = brandMapper.insertCategoryBrand(cid,brand.getId());

            if(count != 1){

                throw new LyException(ExceptionEnum.BRAND_SAVE_ERROR);

            }

        }

    }

    1. brandmapper   新增品牌时,保存品牌的分类

@Insert("INSERTINTOtb_category_brand(category_id,brand_id)VALUES(#{cid},#{bid})")

intinsertCategoryBrand(@Param("cid")Long cid,@Param("bid")Long bid);

    1. 新增品牌时的图片上传
      1. 所有请求zuul网关会通过springmvc对请其及进行预处理,缓存。但如果上传较大的文件时,预处理会导致网关阻塞。所以请求要绕过zuul的请求缓存,直接通过路由到达微服务。
        1. 可以在nginx中,通过rewrite指令对地址进行重写,在nginx.conf的api.leyou.com的server里加入

  location /api/upload {

                        rewrite "^/(.*)$" /zuul/$1;     

        }

    1. FastDFS:分布式文件系统(适合于存取小文件)

HDFS:hadoop的,适合用于存取大文件

    1. 安装fdfs

配置文件在 /etc/fdfs

service fdfs_trackerd start

service fdfs_storaged start

/usr/bin/fdfs_storaged /etc/fdfs/storage.conf start

/usr/bin/fdfs_trackerd /etc/fdfs/tracker.conf start

ps -ef | grep fdfs

测试:在上传目录/tmp下放入一张图片1.jpg

/usr/bin/fdfs_upload_file /etc/fdfs/client.conf /tmp/1.jpg

返回group1/M00/00/00/wKijgFxMOAqAGU4dAABt4YKvarg315.jpg

    1. 安装nigix模块 ,
      1. 添加3个配置到/etc/fdfs

    1. 重新配置nginx

./configure --prefix=/opt/nginx --sbin-path=/usr/bin/nginx --add-module=/home/leyou/fdfs/fastdfs-nginx-module/src

    1. 编译,不安装  nginx make
    2. 复制nginx1.10.0/objs下的nginx二进制文件到usr/bin

可能会报错,要先关闭nginx服务  nginx -s stop 然后复制,再启动

    1. 上传图片业务编写
      1. 使用fastdfs-client来上传到fastDFS
        1. 依赖

<dependency>

<groupId>com.github.tobato</groupId>

<artifactId>fastdfs-client</artifactId>

</dependency>

    1. fastdfs启动类

@Configuration

@Import(FdfsClientConfig.class)

//解决jmx重复注册bean的问题

@EnableMBeanExport(registration=RegistrationPolicy.IGNORE_EXISTING)

publicclassFastClientImporter{

}

    1. 添加配置

fdfs:

  so-timeout: 2500

  connect-timeout: 600

  thumb-image: # 缩略图

    width: 60

    height: 60

  tracker-list: # tracker地址

    - 192.168.163.128:22122

    1. 自定义属性来限制上传的类型和定义url
      1. 添加配置

ly:

  upload:

    baseUrl: http://image.leyou.com/

    ALLOW_TYPES:

      - image/jpeg

      - image/jpg

      - image/png

      - image/bnp

    1. 定义配置类

@ConfigurationProperties(prefix="ly.upload")

@Data

publicclassUploadProperties{

privateStringbaseUrl;

privateList<String>allowTypes;

}

    1. service编写

@Service

@Slf4j

@EnableConfigurationProperties(UploadProperties.class)

publicclassUploadService{

 

//使用自定义配置

@Autowired

private UploadProperties prop;

 

//上传到fdfs

@Autowired

private FastFileStorageClient storageClient;

publicStringuploadImage(MultipartFilefile){

try{

//校验文件类型

StringcontentType=file.getContentType();

if(!prop.getAllowTypes().contains(contentType)){

thrownewLyException(ExceptionEnum.INVALID_FILE_TYPE);

}

 

//校验文件内容

BufferedImageimage=ImageIO.read(file.getInputStream());

if(image==null){

thrownewLyException(ExceptionEnum.INVALID_FILE_TYPE);

}

//上传到FastDFS

//取得后缀

String extension =StringUtils.substringAfterLast(file.getOriginalFilename(),".");

StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(),extension,null);

 

//返回路径

return prop.getBaseUrl()+storePath.getFullPath();

}catch(IOExceptione){

//上传失败

log.error("[文件上传]上传文件失败",e);

throw new LyException(ExceptionEnum.UPLOAD_FILE_ERROR);

}

}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值