生产消费者模式实例(多线程实现价格监控)

主线程 创建多个线程,实现生产数据

package com.megacloud.amazon.business.job;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.ibatis.dao.client.DaoManager;
import com.megacloud.amazon.dao.PriceDao;
import com.megacloud.amazon.entity.OrderSKUManager;
import com.megacloud.amazon.entity.RemeberMonitorOpt;
import com.megacloud.amazon.service.MonitorPriceControlThread;
import com.megacloud.amazon.servlet.InitApp;
import com.megacloud.common.Utils;
import com.megacloud.common.ibatis.BatisManager;

/**
 * 价格监控 主线程
 * 
 * @author Lying
 *
 */
public class PriceMonitorMainThread extends Thread {

	private static Logger logger = Logger.getLogger(PriceMonitorMainThread.class);
	DaoManager daoManager = BatisManager.getDaomanager();
	PriceDao dao=(PriceDao) daoManager.getDao(PriceDao.class);
	private String[] amzApiAuths = new String[3];


	private static List<OrderSKUManager> tobePricedSKUList = new ArrayList<OrderSKUManager>();
	
	@Override
	public void run() {

		amzApiAuths[0] = "A1L0Y1D1711UF5AX;;amzn.mws.74a440c7-1ea0-613e-2b78-dea0ba734wwwba0;;AKIAJN3FDE42JQKSK4JQ;;ihLwRZuXwzh/EX7CC1QGBNNiDOWAT8vseNNlKoHq";
		amzApiAuths[1] = "A2X9wYTU136QT1Z5;;amzn.mws.8ca67c91-ca62-00f2-0e96-ec8437w3cee7e7a;;AKIAIUHPA63HQAT4DKRQ;;0ZDTQNjRpMksByd8hdqzQi6XHCIwA9+xTgcK1U6t";
		amzApiAuths[2] = "A3MXHK6MWOweHLG8;;amzn.mws.02af1af9-9fcc-61a8-e5ed-2wc82a99ww881ce;;AKIAJIDB3GHWBNFPFPXA;;KqrrbIUZDDgyw3FmKrS6RGPqetJr96aOI4qR0PrN";		
		
		int searsId =0;	
		int skuStartId =0;	
		Map<String, Integer> startIdMap = null;
		//创建监控操作的多个线程
		for (int i = 0; i < amzApiAuths.length; i++) {			
			MonitorPriceControlThread t = new MonitorPriceControlThread(amzApiAuths[i]);
			logger.info(t.toString() + "  job is start!");
			t.start();
		}

		// 分批循环取SKU数据
		// SKU记录数消费到低于200条时取下一批。
		while ( true) { 
			if (tobePricedSKUList.size() < 200) {
				//1 对应数据库RemeberMonitorOpt中mark的状态
				RemeberMonitorOpt optSears=dao.getRemeberMonitorOptByMark(1);
				if(optSears!=null){
					searsId=optSears.getMaxId();
				}
				RemeberMonitorOpt opt=dao.getRemeberMonitorOptByMark(2);
				if (opt!=null) {
					skuStartId = opt.getMaxId();
				}
				
				//获取sky存入tobePricedSKUList作为缓存区,返回取的条数
				startIdMap = catchAndPutSKUData(skuStartId,searsId);
				logger.info("doAmzPriceMonitor: catched record max ids walMart is " +
						startIdMap.get("skuStartId") +", Sears is "+ startIdMap.get("searsId"));
				if(startIdMap.get("skuStartId")==0 && opt!=null){
					opt.setMaxId(0);
					dao.updateRemeberMonitorOpt(opt);
				}
				if(startIdMap.get("searsId")==0 && optSears!=null){
					optSears.setMaxId(0);
					dao.updateRemeberMonitorOpt(optSears);
				}
			}
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	
		}
		
	}
	
	

	/**
	 * 获取sku数据(生产数据)
	 * 
	 * @param skuStartId
	 * @return
	 */
	public static Map<String, Integer> catchAndPutSKUData(int skuStartId , int searsId) {
		synchronized (tobePricedSKUList) {
			String sqlGetSKU = "select * from order_skumanager where id > " + skuStartId + " AND status = 1 LIMIT 300";
			List<OrderSKUManager> catchedList = getSKUData(sqlGetSKU);
			String searsSkumanagerSql = "select * from sears_skumanager where id > " + searsId + " AND status = 1 LIMIT 300";
			List<OrderSKUManager> catchedSearsList = getSKUData(searsSkumanagerSql);   
			logger.info("Put SKU Data, Wal_Count = " + catchedList.size()+",Sears_Count = "+catchedSearsList.size());
			tobePricedSKUList.addAll(catchedList);
			tobePricedSKUList.addAll(catchedSearsList);
			logger.info("SKU Data Count Total = " + tobePricedSKUList.size());
			if (catchedList != null && catchedList.size() > 0) {
				skuStartId = tobePricedSKUList.get(catchedList.size() - 1).getId();
			}else{
				// 所有数据已经取完
				skuStartId = 0; 
				}
			if(catchedSearsList != null && catchedSearsList.size() > 0){
				searsId = tobePricedSKUList.get(tobePricedSKUList.size() - 1).getId();
			}else{
				searsId = 0;
			}
		}
		HashMap<String, Integer> startIdMap = new HashMap<String,Integer>();
		startIdMap.put("skuStartId", skuStartId);
		startIdMap.put("searsId", searsId);
		return startIdMap;
	}

	/**
	 * (消费数据)
	 * 
	 * @param recordCount
	 * @return
	 */
	public static List<OrderSKUManager> consumeSKUData(int recordCount) {
		List<OrderSKUManager> consumeData = new ArrayList<OrderSKUManager>();
		synchronized (tobePricedSKUList) {
			if (tobePricedSKUList.size() < recordCount)
				recordCount = tobePricedSKUList.size();
			for (int i = 0; i < recordCount; i++) {
				consumeData.add(tobePricedSKUList.get(0));
				tobePricedSKUList.remove(0);
			}
		}
		return consumeData;
	}
	
	/**
	 * 获取数据连接
	 * @return
	 */
	public static Connection getConnection() {
		String password = "123456";
		String url = "jdbc:mysql://localhost:3306/amazon";
		String username = "root";
		java.sql.Connection con = null;
		boolean flag = true;
		int errorNumber = 0;
		while (flag) {
			try {
				Class.forName("com.mysql.jdbc.Driver");
				con = DriverManager.getConnection(url, username, password);
				flag = false;
			} catch (Exception e) {
				logger.error("连接数据库操作错误:" + e);
				Utils.insertExcep(
						"链接数据库有异常!异常位置为:GetPriceService--getConnection" + "url为:" + url, e.getMessage(), e);
				if (errorNumber == 3) {
					return null;
				} else {
					errorNumber++;
				}
				e.printStackTrace();
				try {
					Thread.sleep(2 * 60 * 1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
		return con;
	}

	/**
	 * 获取数据库orderSkuManager数据
	 * 
	 * @param sql
	 * @return
	 */
	public static List<OrderSKUManager> getSKUData(String sql) {
		List<OrderSKUManager> list = new ArrayList<OrderSKUManager>();
		Connection con = getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			ResultSetMetaData md = rs.getMetaData(); // 获得结果集结构信息,元数据
			int columnCount = md.getColumnCount(); // 获得列数
			while (rs.next()) {
				Map<String, Object> rowData = new HashMap<String, Object>();
				for (int i = 1; i <= columnCount; i++) {
					rowData.put(md.getColumnName(i), rs.getObject(i));
				}
				OrderSKUManager sku = new OrderSKUManager();
				sku.setId((int) rowData.get("id"));
				sku.setSku((String) rowData.get("sku"));
				sku.setOfferLink((String) rowData.get("offerLink"));
				sku.setPurchaseLink((String) rowData.get("purchaseLink"));
				sku.setNewPrice((float) rowData.get("newPrice"));
				sku.setOldPrice((float) rowData.get("oldPrice"));
				sku.setShopname((String) rowData.get("shopname"));
				sku.setAuthor((String) rowData.get("author"));
				sku.setOperationNote((String) rowData.get("operationNote"));
				sku.setAsin((String) rowData.get("asin"));
				sku.setStatus((int) rowData.get("status"));
				sku.setUnpublish((int) rowData.get("unpublish"));
				sku.setRemark((int) rowData.get("remark"));
				sku.setTime((long) rowData.get("time"));

				list.add(sku);
			}
		} catch (Exception e) {
			logger.error("查询数据库数据错误:" + e);
			Utils.insertExcep("查询数据库数据有异常!异常位置为:GetPriceService--getData",
					e.getMessage(), e);
			e.printStackTrace();
		} finally {
			try {
				rs.close();
				pstmt.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	
	
	
	public static void main(String[] args) {
		String dbURL = "database.properties"; // 链接数据库
		BatisManager.init(dbURL);
		new InitApp().initSystemConfig(new InitApp().getClass().getClassLoader().getResource("./").getPath().replaceAll("%20", " ")+ "conf.properties");
		//测试
		new PriceMonitorMainThread().start();
		
		
		
	}

}

次线程获取数据消费数据

package com.megacloud.amazon.service;

import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

import com.amazonservices.mws.products.MarketplaceWebServiceProductsAsyncClient;
import com.amazonservices.mws.products.MarketplaceWebServiceProductsConfig;
import com.amazonservices.mws.products.model.ASINListType;
import com.amazonservices.mws.products.model.GetLowestOfferListingsForASINRequest;
import com.amazonservices.mws.products.model.GetLowestOfferListingsForASINResponse;
import com.amazonservices.mws.products.model.GetLowestOfferListingsForASINResult;
import com.amazonservices.mws.products.model.LowestOfferListingList;
import com.amazonservices.mws.products.model.LowestOfferListingType;
import com.amazonservices.mws.products.model.MoneyType;
import com.amazonservices.mws.products.model.PriceType;
import com.amazonservices.mws.products.model.Product;
import com.amazonservices.mws.products.model.QualifiersType;
import com.amazonservices.mws.products.model.ShippingTimeType;
import com.ibatis.dao.client.DaoManager;
import com.megacloud.amazon.business.job.PriceMonitorMainThread;
import com.megacloud.amazon.dao.PriceDao;
import com.megacloud.amazon.entity.APIException;
import com.megacloud.amazon.entity.OrderSKUManager;
import com.megacloud.amazon.entity.RemeberMonitorOpt;
import com.megacloud.common.Utils;
import com.megacloud.common.ibatis.BatisManager;


/**
 * 价格监控线程
 * @author Administrator
 *
 */
public class MonitorPriceControlThread extends Thread{
	private static Logger logger = Logger.getLogger(MonitorPriceControlThread.class);
	DaoManager daoManager = BatisManager.getDaomanager();
	PriceDao dao=(PriceDao) daoManager.getDao(PriceDao.class);

	private  String sellerId;
	private  String mwsAuthToken;
	private  String accessKeyId; 
	private  String secretAccessKey; 
	
	private static int  recordCount = 20;		// 每次监控取20条数据  	不能超过30
	private static String appName = "MaiAPP";	
	private static String appVersion = "1.0";
	private static String endpoint="https://mws.amazonservices.com";
	private static String marketplaceId="ATVPDKIKX0DER";
	private static String itemCondition="new";
	
	/**
	 * 线程标标识
	 */
	public String toString(){	
		return "Price Monitor Thread " + sellerId;
	}
	
	/**
	 * 构造方法(对apiAuth进行转成参数)
	 * @param apiAuth
	 * @param startId
	 */
	public  MonitorPriceControlThread(String apiAuth) {
		String apiAuths[]=apiAuth.split(";;");
		this.sellerId = apiAuths[0];
		this.mwsAuthToken = apiAuths[1];
		this.accessKeyId = apiAuths[2];
		this.secretAccessKey = apiAuths[3];
	}

	@Override
	public void run() {
		int timesNo = 0;
		while(true){
			System.out.println(this.toString() + " consume sku data, Times No: " + ++timesNo);
			List<OrderSKUManager> skus = PriceMonitorMainThread.consumeSKUData(recordCount);					
			System.out.println(this.toString() + " " + skus.size());
				try {
					insertPrice(skus);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			System.out.println(this.toString() + " consume sku data end, Times No: " + timesNo);
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	 
/**
 * 	进行价格监控的逻辑操作
 * @param sellerId
 * @param mwsAuthToken
 * @param accessKeyId
 * @param secretAccessKey
 * @param remark
 * @param startId  首次取600条SKU记录供消费者使用,查询价格。
 * @throws Exception 
 */
	private  void insertPrice(List<OrderSKUManager> list) throws Exception{// 获取可消费的监控数据,用来去api监控价格   拼成asinString
		Map<String, Map<String, String>> priceMaps=new HashMap<String, Map<String,String>>();
		Map<String, Map<String, String>> asinsPriceMap=new HashMap<String, Map<String,String>>();
		MonitorInfo MonitorInfo = new MonitorInfo();
		String asinString="";
		String collectPrice="";//存入采到的价格
		String pricemark= "";//标记sku去自己平台返回状态
		
		for (int j = 0; j < list.size(); j++) {
			String asinstr=(String) list.get(j).getAsin();
			if (asinstr!=null)
			asinString+=asinstr+",";
		}
		// 去获取10个Asin的价格,除掉sku为null的值	
		if(!asinString.equals("")){		
			priceMaps=getAsinPrice(accessKeyId, secretAccessKey, sellerId, mwsAuthToken, asinString);
			asinsPriceMap.putAll(priceMaps);
		}
		for(int i=0;i<list.size();i++){
			String recordStr="";
			int id=(int) list.get(i).getId();
			int status=(int) list.get(i).getStatus();					// 0,1两种状态 0:系统认为下架(unpublish),1:系统认为上架(publish)
			int unpublish= (int) list.get(i).getUnpublish();		    // 0,1两种状态 0:系统认为有库存,1:系统认为没有有库存
			String sku = list.get(i).getSku();							// 自己产品编号
			float oldMonitorPrice =(float) list.get(i).getOldPrice(); 	// 供应商的价格
			float newPrice =(float) list.get(i).getNewPrice();			// 自己平台的价格
			int remark = (int) list.get(i).getRemark();					// sku价格变动记录
			String shopname = list.get(i).getShopname();				// 店铺名称
			String listingLink = list.get(i).getListingLink();			// 产品的平台链接(该sku在我们上传平台上的链接)
			String asin=(String) list.get(i).getAsin();					// 产品独有的编码,来源于产品原网站
			String offerLink=(String) list.get(i).getOfferLink();		// 亚马逊产品的跟卖链接(其他平台的sku现在有可能没有)
			String purchaseLink=(String) list.get(i).getPurchaseLink();	// 优选采购链接
			long time = (long) list.get(i).getTime();					// 上传时间(bigInt)
			String author=(String) list.get(i).getAuthor();				// 上传该sku的用户
			String operationNote=(String) list.get(i).getOperationNote();// api对这个sku进行的操作记录
	
		
				Map<String, String> priceMap = asinsPriceMap.get(asin);
				if (priceMap==null || priceMap.get("status") .equalsIgnoreCase("NotExist") ) {
					unShelveProduct(shopname,sku);
					operationNote = "This sku's ASIN has been removed!";
						MonitorInfo.updateOrderSkuManagerByAsin(operationNote,asin);
					continue;
				}else if(priceMap.get("status") .equalsIgnoreCase("Failed")){
					unShelveProduct(shopname,sku);
					operationNote = "ASIN of this sku is wrong!";
						MonitorInfo.updateOrderSkuManagerByAsin(operationNote,asin);
					continue;
				}
				if(shopname == null || shopname.equals("")){
					operationNote = "This sku's shopname is empty!"; 
						MonitorInfo.updateOrderSkuManagerByAsin(operationNote,asin);
					continue;
				}
								
				// 所需采到的价格
				if(shopname.contains("Walmart")){
					collectPrice = priceMap.get("FBM");//采到的价格
				}else if(shopname.contains("Sears")){
					collectPrice = priceMap.get("FBA");
				}
				if (collectPrice.contains("监控") || collectPrice==null || collectPrice.equals("")) {
					unShelveProduct(shopname,sku);
					operationNote="only FBA !";
						MonitorInfo.updateOrderSkuManagerByAsin(operationNote,asin);
					continue;
				}
				
				float newMonitorPrice=Float.parseFloat(collectPrice);
				float systemPrice=0;
				//调用调价公式,进行调价
				if (newMonitorPrice - oldMonitorPrice>0.5 && -0.5>newMonitorPrice - oldMonitorPrice){//本次监控价比上次超过0.5的话,调价
				systemPrice=AddPrice(newMonitorPrice);
				String	hprice=String.valueOf((float)(Math.round(systemPrice*1.5*100))/100);
				//通过api去walMart调价
				
				OrderSKUManager osm = new OrderSKUManager();
				osm.setAsin(asin);
				osm.setAuthor(author);
				osm.setSku(sku);
				osm.setOldPrice(oldMonitorPrice);
				osm.setNewPrice(newPrice);
				osm.setTwoSellPrice(systemPrice);
				osm.setNewMonitorPrice(newMonitorPrice);
				osm.setShopname(shopname);
				osm.setId(id);
				
				if (!shopname.contains("Sears")){
				String priceflag=WalMart.modfiyPrice(shopname, sku, asin, String.valueOf(systemPrice), hprice);
				if(priceflag.equalsIgnoreCase("OK")){//修改系统中sku的状态
					pricemark="Yes";
				}else if(priceflag.equalsIgnoreCase("Invalid")){//沃尔玛没有这个sku
					pricemark="Invalid";
				}else{
					pricemark="No";
					}
				/*String stockmark = null;
				if(pricemark.equals("Yes") && status==0){//下架了的产品 只有价格修改成功后才上架
					String stockflag=WalMart.UnShelveProduct(shopname, sku, "批量价格监控", 1000);
					if(stockflag.equalsIgnoreCase("OK")){//修改系统中sku的状态
						status=1;
						unpublish=0;
						stockmark="Yes";
					}else{
						stockmark="No";
					}
				}*/
				if(pricemark.equals("Yes")){
						operationNote="walMart had upShelf, price changes:"+newPrice+"———>"+systemPrice+"Change the time:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
						recordStr=asin+";;"+status+";;"+unpublish+";;"+newMonitorPrice+";;"+systemPrice+";;"+operationNote+";;"+ ++remark;
						osm.setNotes(operationNote);
						MonitorInfo.updateInfo(recordStr ,osm);
				}/*else if(pricemark.equals("Yes") && stockmark.equals("No") ){
					operationNote="上架失败,价格变化:"+newPrice+"———>"+systemPrice+"修改时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				}else if(pricemark.equals("Yes") && stockmark.equals("")){
					operationNote="价格变化:"+newPrice+"———>"+systemPrice+"修改时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				}*/
				if(pricemark.equals("No")){
					// systemPrice;本次查价调价后/预售价		newPrice 自己平台上次售价
					//newMonitorPrice;本次api查的价		oldMonitorPrice 供应商的价格(老的监控价格)
						String description = "API Modified price exception!"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());  //描述
						recordStr=asin+";;"+status+";;"+unpublish+";;"+newMonitorPrice+";;"+systemPrice+";;"+description+";;"+ ++remark;
						osm.setNotes(description);
						MonitorInfo.updateInfo(recordStr,osm);
				}else if(pricemark.equals("Invalid")){//监控到无效的sku
						String invalid = "Invalid sku monitored!";
						MonitorInfo.changeInfo(asin,invalid);
						}
					}else{
						operationNote="Sears had upShelf, price changes"+newPrice+"———>"+systemPrice+"Change the time:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
						recordStr=asin+";;"+status+";;"+unpublish+";;"+newMonitorPrice+";;"+systemPrice+";;"+operationNote+";;"+ ++remark;
						osm.setNotes(operationNote);
						MonitorInfo.updateInfo(recordStr ,osm);
						}
				}
				// 记录wal_orderId
				if (!shopname.contains("Sears")) {
					RemeberMonitorOpt opt=dao.getRemeberMonitorOptByMark(2);
					if(opt!=null){
						opt.setMaxId(id);
						dao.updateRemeberMonitorOpt(opt);
					}
				}else{// 记录SearsId
					RemeberMonitorOpt opt=dao.getRemeberMonitorOptByMark(1);
					if(opt!=null){
						opt.setMaxId(id);
						dao.updateRemeberMonitorOpt(opt);
					}
				}
				
				
				
			}
		}
				
		//getPriceFromAmz
		//adjustPriceWalmart
		//updateSkuInfo

	/**
	 * 通过api获取Asin价格
	 * @param accessKeyId
	 * @param secretAccessKey
	 * @param sellerId
	 * @param mwsAuthToken
	 * @param asinStr
	 * @return
	 */
	public Map<String, Map<String, String>> getAsinPrice(
			String accessKeyId,String secretAccessKey,String sellerId,String mwsAuthToken,String asinStr){
		Map<String, Map<String, String>> returnMap=new HashMap<String, Map<String,String>>();
		String[] asins=asinStr.split(",");
		//去重  
		/*List<String> list = new ArrayList<String>();  
		for(int i=0;i<asin1.length;i++){  
		    for(int j=i+1;j<asin1.length;j++){  
		        if(asin1[i] == asin1[j]){  
		            j = ++i;  
		        }  
		    }  
		    list.add(asin1[i]);  
		}  
		String[] asins = (String[]) list.toArray(new String[list.size()]);  
		*/
		int errorNumber=0;
		while(true){
			try {
				Thread.sleep(2000);
				GetLowestOfferListingsForASINResponse response = MonitorPriceControlThread.invokeGetLowestOfferListingsForASIN(
						accessKeyId,secretAccessKey,endpoint, sellerId, mwsAuthToken, marketplaceId, asins, itemCondition, false);
				List<GetLowestOfferListingsForASINResult> resultList = response.getGetLowestOfferListingsForASINResult();
				for(GetLowestOfferListingsForASINResult result:resultList){
					Map<String, String> map = new HashMap<String, String>();
					String userrorDes="";
					String fbaerrorDes="";
					String usPrice="";
					String fbaPrice="";
					String status=result.getStatus();
					String asin=result.getASIN();
					boolean usflag=false;
					boolean fbaflag=false;
					if(status.equalsIgnoreCase("ClientError")){
						map.put("status","Failed");
						returnMap.put(asin, map);
						continue;
					}else if(status.equalsIgnoreCase("Success")){
						Product product = result.getProduct();
						LowestOfferListingList offerList = product.getLowestOfferListings();
						List<LowestOfferListingType> offerTypeList = offerList.getLowestOfferListing();
						if(offerTypeList.size()==0){
							map.put("status","NotExist");
							returnMap.put(asin, map);
							continue;
						}else{
							map.put("status","Success");
						}
						for(LowestOfferListingType offer:offerTypeList){
							QualifiersType type = offer.getQualifiers();
							String positiveFeedbackRating = type.getSellerPositiveFeedbackRating();
							ShippingTimeType shippingTime = type.getShippingTime();
							String fulfillmentChannel = type.getFulfillmentChannel();
							String shipsDomestically = type.getShipsDomestically();
							String time=shippingTime.getMax();
							int feedbackCount = offer.getSellerFeedbackCount();
							if(positiveFeedbackRating.contains("-") && positiveFeedbackRating.contains("%")){
								positiveFeedbackRating=positiveFeedbackRating.substring(positiveFeedbackRating.lastIndexOf("-")+1, positiveFeedbackRating.lastIndexOf("%"));
							}
							if(fbaflag==false && fulfillmentChannel.equalsIgnoreCase("Amazon")){
								fbaflag=true;
								PriceType priceType = offer.getPrice();
								MoneyType moneyType = priceType.getLandedPrice();
								BigDecimal bigDecimal = moneyType.getAmount();
								fbaPrice =bigDecimal.toString();
								map.put("FBA", fbaPrice);
								continue;
							}
							if(!fulfillmentChannel.equalsIgnoreCase("Amazon")){
								if(time.contains("14 or more days") || time.contains("8-13")){
									if(!userrorDes.contains("监控到有配送时间过长!")){
										userrorDes+="监控到有配送时间过长!";
									}
									continue;
								}
								if(positiveFeedbackRating.contains("Less than") || positiveFeedbackRating.contains("Just Launched") || Integer.parseInt(positiveFeedbackRating)<80){
									if(!userrorDes.contains("监控到店铺好评不足!")){
										userrorDes+="监控到店铺好评不足!";
									}
									continue;
								}
								if(feedbackCount<100){
									if(!userrorDes.contains("监控到feedbback低于100!")){
										userrorDes+="监控到feedbback低于100!";
									}
									continue;
								}
							}
							if(usflag==false && fulfillmentChannel.equalsIgnoreCase("Merchant") && (shipsDomestically.equalsIgnoreCase("True") || shipsDomestically.equalsIgnoreCase("Unknown"))){
								usflag=true;
								PriceType priceType = offer.getPrice();
								MoneyType moneyType = priceType.getLandedPrice();
								BigDecimal bigDecimal = moneyType.getAmount();
								usPrice=bigDecimal.toString();
								map.put("FBM", usPrice);
							}
							if(fbaflag && usflag){
								break;
							}
						}
						if(fbaflag && !usflag){//有FBA没有FBM
							if(userrorDes.equals("")){
								map.put("FBM", "监控到没有FBM卖家");
							}else{
								map.put("FBM", userrorDes);
							}
						}else if(!fbaflag && usflag){//没有FBA有FBM
							if(fbaerrorDes.equals("")){
								map.put("FBA", "监控到没有FBA卖家");
							}else{
								map.put("FBA", fbaerrorDes);
							}
						}else if(!fbaflag && !usflag){
							if(fbaerrorDes.equals("")){
								map.put("FBA", "监控到没有FBA卖家");
							}else{
								map.put("FBA", fbaerrorDes);
							}
							if(userrorDes.equals("")){
								map.put("FBM", "监控到没有FBM卖家");
							}else{
								map.put("FBM", userrorDes);
							}
						}
						returnMap.put(asin, map);
					}
				}
				break;
			} catch (Exception e) {
				e.printStackTrace();
				Utils.insertExcep("亚马逊API价格监控有异常!=== asin串==="+asinStr,e.getMessage(),e);
				if(e.getMessage().contains("Request is throttled")){
					try {
						Thread.sleep(5*60*1000);
						if(errorNumber==2){
							break;
						}else{
							errorNumber++;
						}
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
				}else{
					break;
				}
			}
		}
		return returnMap;
	}
	

	/**
	 * 调用  获取ASIN 的最低报价响应
	 * @param accessKeyId
	 * @param secretAccessKey
	 * @param endpoint
	 * @param sellerId
	 * @param mwsAuthToken
	 * @param marketplaceId
	 * @param asins
	 * @param itemCondition
	 * @param excludeMe
	 * @return
	 */
	public static GetLowestOfferListingsForASINResponse invokeGetLowestOfferListingsForASIN(String accessKeyId,String secretAccessKey,String endpoint, String sellerId,String mwsAuthToken,String marketplaceId,String[] asins,String itemCondition,boolean excludeMe){
		MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig();
		config.setServiceURL(endpoint);// 设置服务连接路径
		// Set other client connection configurations here.
		// 连接到客户端,获取api连接
		MarketplaceWebServiceProductsAsyncClient client = new MarketplaceWebServiceProductsAsyncClient(accessKeyId, secretAccessKey, appName, appVersion, config, null);
		//创建 获取最低价格的请求 的对象
		GetLowestOfferListingsForASINRequest request = new GetLowestOfferListingsForASINRequest();            
		request.setSellerId(sellerId);            
		request.setMWSAuthToken(mwsAuthToken);            
		request.setMarketplaceId(marketplaceId);
		ASINListType asinList = new ASINListType();
		for(String asin : asins){
			asinList.withASIN(asin);
		}
		request.setASINList(asinList);            
		request.setItemCondition(itemCondition);            
		request.setExcludeMe(excludeMe);

		return client.getLowestOfferListingsForASIN(request);
	}

	
	/**
	 * 调价公式
	 * @param price
	 * @param type
	 * @return
	 */
	public float AddPrice(float price) {
		if(price<=5){
				price = price +  3;
		}else if(price>5&&price<=10){
				price = price *1.48f;
		}else if(price>10&&price<=15){
				price = price *1.35f;
		}else if(price>15&&price<=20){
				price = price *1.34f;
		}else if(price>20&&price<=25){
				price = price *1.33f;
		}else if(price>25&&price<=30){
				price = price *1.32f;
		}else if(price>30&&price<=35){
				price = price *1.31f;
		}else if(price>35&&price<=40){
				price = price *1.30f;
		}else if(price>40&&price<=45){
				price = price *1.29f;
		}else if(price>45&&price<=50){
				price = price *1.28f;
		}else if(price>50){
				price = price *1.27f;
		}
		DecimalFormat df = new DecimalFormat("#.00"); 
		String text = df.format(price);
		price = Float.valueOf(text);
		int index = text.indexOf(".");
		String t1 = text.substring(0,index);
		String t2 = text.substring(index+1,text.length());
		String t3 = text.substring(index+2,text.length());
		String t4 = text.substring(index+1,text.length()-1);
		if(t4.equals("0")&&t3.equals("0")){
			int small = Integer.parseInt(t2);
			int fi = Integer.parseInt(t1);
			if(small==0){					
				fi = fi - 1;
				price = fi+0.99f;
			}else{
				price = fi +0.09f;
			}	
			return price;
		}else{
			t3 = "0.0" + t3;
			float abc = Float.valueOf(t3);
			price = Float.valueOf(text);
			price = price -abc +0.09f;
			return price;
		}

	}



	/**
	 * 去walMart下架产品
	 * @param shopname
	 * @param sku
	 */
	private void unShelveProduct(String shopname , String sku) {
		if(!shopname.contains("Sears")){
			String stockflag=WalMart.UnShelveProduct(shopname, sku, sku+"下架产品", 0);// 产品下架  此处0的时候代表去下架,1000的时候去上架
			if(stockflag.equalsIgnoreCase("OK")){
				logger.info("The success of the shelves!");
			}else{
				logger.info("Failed to drop!");
			}
		}
	}
	
	
	public static void main(String[] args) throws IOException, URISyntaxException {
		
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lying~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值