所有代码发布在 [https://github.com/hades0525/leyou]
Day07
2019年1月24日
21:47
品牌管理
-
- 查询和搜索
- BrandMapper
- 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)); } | ||||
-
- 分页类(放在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; } |
-
- 如果有自定义的构造函数(不是空参或全参),就不能再使用lombok的构造函数注解,会报错
- 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; }) } } |
-
- 新增
- 新增品牌分类级联选择:cascader.vue(自定义的)
- brandcontroller 新增品牌时,传入的参数(brand对象,分类的ids)
- 新增品牌分类级联选择:cascader.vue(自定义的)
- 新增
@PostMapping publicResponseEntity<Void>saveBrand(Brandbrand,@RequestParam("cids")List<Long>cids){ brandService.saveBrand(brand,cids); returnResponseEntity.status(HttpStatus.CREATED).build(); } |
-
- 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); } } } |
-
- brandmapper 新增品牌时,保存品牌的分类
@Insert("INSERTINTOtb_category_brand(category_id,brand_id)VALUES(#{cid},#{bid})") intinsertCategoryBrand(@Param("cid")Long cid,@Param("bid")Long bid); |
-
- 新增品牌时的图片上传
- 所有请求zuul网关会通过springmvc对请其及进行预处理,缓存。但如果上传较大的文件时,预处理会导致网关阻塞。所以请求要绕过zuul的请求缓存,直接通过路由到达微服务。
- 可以在nginx中,通过rewrite指令对地址进行重写,在nginx.conf的api.leyou.com的server里加入
- 所有请求zuul网关会通过springmvc对请其及进行预处理,缓存。但如果上传较大的文件时,预处理会导致网关阻塞。所以请求要绕过zuul的请求缓存,直接通过路由到达微服务。
- 新增品牌时的图片上传
location /api/upload { rewrite "^/(.*)$" /zuul/$1; } |
-
- FastDFS:分布式文件系统(适合于存取小文件)
HDFS:hadoop的,适合用于存取大文件
-
- 安装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
-
- 安装nigix模块 ,
- 添加3个配置到/etc/fdfs
- 安装nigix模块 ,
-
- 重新配置nginx
./configure --prefix=/opt/nginx --sbin-path=/usr/bin/nginx --add-module=/home/leyou/fdfs/fastdfs-nginx-module/src
-
- 编译,不安装 nginx make
- 复制nginx1.10.0/objs下的nginx二进制文件到usr/bin
可能会报错,要先关闭nginx服务 nginx -s stop 然后复制,再启动
-
- 上传图片业务编写
- 使用fastdfs-client来上传到fastDFS
- 依赖
- 使用fastdfs-client来上传到fastDFS
- 上传图片业务编写
<dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> </dependency> |
-
- fastdfs启动类
@Configuration @Import(FdfsClientConfig.class) //解决jmx重复注册bean的问题 @EnableMBeanExport(registration=RegistrationPolicy.IGNORE_EXISTING) publicclassFastClientImporter{ } |
-
- 添加配置
fdfs: so-timeout: 2500 connect-timeout: 600 thumb-image: # 缩略图 width: 60 height: 60 tracker-list: # tracker地址 - 192.168.163.128:22122 |
-
- 自定义属性来限制上传的类型和定义url
- 添加配置
- 自定义属性来限制上传的类型和定义url
ly: upload: baseUrl: http://image.leyou.com/ ALLOW_TYPES: - image/jpeg - image/jpg - image/png - image/bnp |
-
- 定义配置类
@ConfigurationProperties(prefix="ly.upload") @Data publicclassUploadProperties{ privateStringbaseUrl; privateList<String>allowTypes; } |
-
- 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); } } |