相片的上传与处理(springcloud与mongo集合)

1、引入mongo依赖

    <!-- mongodb依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

2、配置mongo数据库配置以及文件大小设置

---  
spring:
  data:
    mongodb:
      uri: mongodb://localhost:27017/cust
  http:
    multipart:
      max-file-size: 500Mb
      max-request-size: 500Mb

  datasource:
    name: mydb
    type: com.zaxxer.hikari.HikariDataSource
    url: jdbc:mysql://127.0.0.1:3306/custdb?characterEncoding=utf8&useSSL=false
    username: root
    password: root
    driverClassName: com.mysql.jdbc.Driver
    minIdle: 5
    maxActive: 10
    initialSize: 1
    timeBetweenEvictionRunsMillis: 3000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
  rabbitmq:
    host: localhost
    port: 5672
    username: zhb
    password: zhb
    virtual-host: cloud-zhb

mybatis:
  #姝ら厤缃厤鍚坸mlUserMapper鐨勪娇鐢�
  mapperLocations: classpath:/mappers/*.xml
  typeAliasesPackage: com.bincai.cloud.cust.domain.model
eureka:
  instance:
    preferIpAddress: true
    metadata-map:
      cluster: MAIN
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
 

3、引入MongoTemplate以及PhotosVO

PhotosVO.java

package com.bincai.cloud.cust.domain.common;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel
public class PhotosVO {
    @ApiModelProperty(value="图片id")
    private String _id;
    private String _class=null;
    @ApiModelProperty(value="图片所有者")
    private String whose;
    @ApiModelProperty(value="图片文本")
    private String photo;
    @ApiModelProperty(value="图片文件")
    public String get_class() {
        return _class;
    }
    public void set_class(String _class) {
        this._class = _class;
    }
    public String get_id() {
        return _id;
    }
    public void set_id(String _id) {
        this._id = _id;
    }
    public String getWhose() {
        return whose;
    }
    public void setWhose(String whose) {
        this.whose = whose;
    }
    public String getPhoto() {
        return photo;
    }
    public void setPhoto(String photo) {
        this.photo = photo;
    }
}
 

MongoDB.java

package com.bincai.cloud.cust.domain.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

@Component
public class MongoDB {
    private final MongoTemplate mongoTemplate;
    @Autowired
    public MongoDB(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }
    public MongoTemplate getMongoTemplate() {
        return mongoTemplate;
    }
}
 

 

4、服务和controller配置

PhotoService.java

package com.bincai.cloud.cust.domain.service;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import com.bincai.cloud.cust.domain.common.MongoDB;
import com.bincai.cloud.cust.domain.common.PhotosVO;

@Service
public class PhotoService {
    @Resource
    private MongoDB mongoDB;
    public static final Logger logger=LoggerFactory.getLogger(PhotoService.class);
    public String savephoto(PhotosVO photosVO){
        logger.info("开始保存照片");
        MongoTemplate mongoTemplate = mongoDB.getMongoTemplate();
        try {
            photosVO.set_id(UUID.randomUUID().toString().replace("-", ""));
            mongoTemplate.insert(photosVO, "photos");
        } catch (Exception e) {
            logger.warn("mongo存储照片时发生异常"+e);
            logger.info("保存照片结束");
            return "error";
        }
        logger.info("保存照片结束");
        return "success";
    }
}
 

CustomerController.java

package com.bincai.cloud.cust.domain.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;


import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bincai.cloud.cust.domain.model.Customer;
import com.bincai.cloud.cust.domain.service.CustService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/cust")
@Api(value="cust",description="客户领域服务接口")
public class CustomerController {
    @Resource
    private CustService custService;

    @ApiOperation(value="客户新增服务",notes="客户新增服务接口")
    @ApiImplicitParam(name="customer",value="客户数据对象JSON",required=true,paramType="body")
   @RequestMapping(value="/api/v1/customers",method=RequestMethod.POST)
   @HystrixCommand(fallbackMethod = "hystrixjsonQuery")
   public String register(@RequestBody String customerInfo){
      Customer customer=JSON.parseObject(customerInfo, Customer.class);
    customer.setId(UUID.randomUUID().toString().replace("-", ""));
        String result=custService.register(customer);    
        return result;       
   }
    @ApiOperation(value="客户信息修改",notes="客户信息变更接口")
    @ApiImplicitParam(name="customerInfo",value="客户信息JSON",required=true,paramType="body")
   @RequestMapping(value="/api/v1/customers/{id}",method=RequestMethod.PUT)
   @HystrixCommand(fallbackMethod = "hystrixjsonQuery")
   public String alter(@RequestBody String customerInfo){
       Customer customer=JSON.parseObject(customerInfo, Customer.class);
        String result=custService.alter(customer);    
        return result;
   }
    @ApiOperation(value="客户信息查询",notes="客户信息查询接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name="name",value="客户姓名",required=false,paramType="query",dataType="String")
})
    @RequestMapping(value = "/api/v1/customers", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @HystrixCommand(fallbackMethod = "searchhystrixjsonQuery")
    public String search(Customer customer) {
        if(customer.getPageIndex()!=null&&customer.getPageSize()!=null){
            customer.offset();
        }
        List<Customer> list = custService.search(customer);
        String Array =JSONArray.toJSONString(list);
        return Array;
    }
    @ApiOperation(value="单个客户信息查询",notes="单个客户信息查询接口")
   @RequestMapping(value="/api/v1/customers/{id}",method=RequestMethod.GET)
   @HystrixCommand(fallbackMethod = "hystrixidQuery")
   public String getById(@PathVariable("id") String id){
       Customer cust = custService.getById(id);
       String result = JSONObject.toJSONString(cust);
        return result;
   }
    @ApiOperation(value="客户信息总条数查询",notes="客户信息总条数查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name="name",value="客户名称",required=false,paramType="query",dataType="String")
    })
    @RequestMapping(value = "/api/v1/customers/counts", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @HystrixCommand(fallbackMethod = "searchhystrixjsonQuery")
    public String searchCount(Customer customer) {
        if(customer.getPageIndex()!=null&&customer.getPageSize()!=null){
            customer.offset();
        }
        int count = custService.searchCount(customer);
        return String.valueOf(count);
    }
    @ApiOperation(value="删除单个公客户信息",notes="删除单个公客户信息接口")
   @RequestMapping(value="/api/v1/customers/{id}",method=RequestMethod.DELETE)
   @HystrixCommand(fallbackMethod = "hystrixidQuery")
   public String delete(@PathVariable("id") String id) throws UnsupportedEncodingException{
       String result=  custService.delete(id);         
         return result;
   }
    
    public String hystrixQuery()
    {
        return "{\"result\":\"error\"}";
    }
    public String hystrixidQuery(String id)
    {
        return "{\"result\":\"error\"}";
    }
    public String hystrixjsonQuery(String customerInfo)
    {
        return "{\"result\":\"error\"}";
    }
    public String searchhystrixjsonQuery(Customer customer)
    {
        return "{\"result\":\"error\"}";
    }
}
 

5、Swagger-ui展示

115031_Q8zh_2404345.png

6、数据库存储

图片采用mongoTemplate的collection存储方式,mongo限制文件大小在4M以下;如果是文件的话最好GridFS文件方式存储。

115048_k4LM_2404345.png

转载于:https://my.oschina.net/Seaside20151225/blog/745305

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值