Spting使用memcached

applicationContext.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

          <!-- 读取项目的资源配置 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
                <!-- <value>classpath:mail.properties</value> -->
                <!-- <value>classpath:memcached.properties</value> -->
            </list>
        </property>
    </bean>

    <!-- JDBC数据源 -->
    <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql://localhost:3306/springtest" />
      <property name="username" value="xuan" />
      <property name="password" value="123456" />
      <property name="testWhileIdle" value="true" />
      <property name="testOnBorrow" value="true" />
      <property name="testOnReturn" value="false" />
      <property name="validationQuery" value="SELECT 1" />
      <property name="validationInterval" value="30000" />
      <property name="timeBetweenEvictionRunsMillis" value="30000" />
      <property name="maxActive" value="100" />
      <property name="minIdle" value="2" />
      <property name="maxWait" value="10000" />
      <property name="initialSize" value="4" />
      <property name="removeAbandonedTimeout" value="60" />
      <property name="removeAbandoned" value="true" />
      <property name="logAbandoned" value="true" />
      <property name="minEvictableIdleTimeMillis" value="30000" />
      <property name="jmxEnabled" value="true" />
    </bean>

    <!-- 事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 事务模板 -->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager" />
        <property name="timeout" value="10"></property>
        <property name="isolationLevelName" value="ISOLATION_READ_COMMITTED"></property>
    </bean>

    <!-- 配置支持注解方式声明事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- MemcachedClient配置 -->
	<bean id="memcachedClient" class="net.spy.memcached.spring.MemcachedClientFactoryBean">
		<property name="servers" value="127.0.0.1:11211" />
		<property name="protocol" value="BINARY" />
		<property name="transcoder">
			<bean class="net.spy.memcached.transcoders.SerializingTranscoder">
				<property name="compressionThreshold" value="1024" />
			</bean>
		</property>
		<property name="opTimeout" value="3000" />
		<property name="timeoutExceptionThreshold" value="1998" />
		<property name="locatorType" value="CONSISTENT" />
		<property name="failureMode" value="Redistribute" />
		<property name="useNagleAlgorithm" value="false" />
	</bean>

</beans>

在Java类文件使用:

package com.grab.video.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.spy.memcached.MemcachedClient;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class GrabVideoController {

	private static final Logger LOG = LoggerFactory.getLogger(GrabVideoController.class);

	private static String filePath="D:\\logs\\video";
	//private static String filePath = "/home/grabVideo/";

	@Autowired
    private MemcachedClient memcachedClient;

	@Autowired
	ServletContext context;

	/**
	 * 输入userid能够使用
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/grab/login", method = { RequestMethod.GET })
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
		String userId = ServletRequestUtils.getStringParameter(request, "userId", "");
		String ts = ServletRequestUtils.getStringParameter(request, "ts", "");
		String sign = ServletRequestUtils.getStringParameter(request, "sign", "");

		ModelAndView mav = new ModelAndView();
		// 身份验证
		if (StringUtils.isNotBlank(userId)) {
			String encryptedSign = EncryptionUtils.md5Hex(ts + userId + "grab");
			if (sign.equals(encryptedSign)) {
				memcachedClient.set("userId", 5*24*60*60, userId);//缓存为有效时间为5日
				//HttpSession session = request.getSession();
				//session.setMaxInactiveInterval(5*24*60*60);//秒为单位,设置session周期为5天
				//session.setAttribute("userId", userId);// 把userId存放到session
				String url = "/grab/import";
				mav.setView(new RedirectView(url));
				return mav;
			}
		}

		mav.setViewName("video/error");
		return mav;
	}

	/**
	 * 导入文件
	 *
	 * @return
	 */
	@RequestMapping(value = "/grab/import", method = { RequestMethod.GET })
	public ModelAndView importFile(HttpServletRequest request, HttpServletResponse response) {
		// String userId = ServletRequestUtils.getStringParameter(request,
		// "userId", null);
		ModelAndView mav = new ModelAndView();
		//HttpSession session = request.getSession();

		String userId = null;
		if (memcachedClient.get("userId") != null) {
			userId = (String) memcachedClient.get("userId");
			SqlFileList sqlFileList = new SqlFileList();
			List<FileListModel> list = new ArrayList<FileListModel>();
			try {
				list = sqlFileList.selectDate(userId);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// 从POLYV的API获取文件夹

			mav.addObject("list", list);
			mav.addObject("userId", userId);
			mav.setViewName("video/import");
			return mav;
		}

		mav.setViewName("video/login");
		return mav;

	}

	/**
	 * 删除文件
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/grab/delete/file", method = { RequestMethod.GET })
	public ResponseEntity<AjaxPostResponse> deleteFile(HttpServletRequest request,
			HttpServletResponse response) {
		String fileId = ServletRequestUtils.getStringParameter(request, "fileId", null);

		MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(mediaType);

		SqlFileList sqlFileList = new SqlFileList();
		try {
			sqlFileList.deleteDate(fileId);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		AjaxPostResponse resp = new AjaxPostResponse("yes");
		return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
	}

	/**
	 * 解析文件
	 *
	 * @return
	 */
	@RequestMapping(value = "/grab/analysis", method = { RequestMethod.GET })
	public ResponseEntity<AjaxPostResponse> analysisFile(HttpServletRequest request,
			HttpServletResponse response) {
		Integer fileId = ServletRequestUtils.getIntParameter(request, "fileId", 0);
		String fileUrl = ServletRequestUtils.getStringParameter(request, "fileUrl", "");
		String classifyId = ServletRequestUtils.getStringParameter(request, "classifyId",
				"classifyId");
		String classifyName = ServletRequestUtils.getStringParameter(request, "classifyName", "");
		String userId = ServletRequestUtils.getStringParameter(request, "userId", null);

		MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(mediaType);

		List<String> urlList = new ArrayList<String>();
		List<String> titleList = new ArrayList<String>();
		try {
			URL url = new URL(fileUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "GBK"));

			String line = null;
			while ((line = reader.readLine()) != null) {
				String str = line;
				//
				String urlstr = str.substring(0, str.indexOf(","));
				String title = str.substring(str.lastIndexOf(",") + 1, str.length());
				//
				urlList.add(urlstr);
				titleList.add(title);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			LOG.info("文件解析失败:" + e);
			e.printStackTrace();
			AjaxPostResponse resp = new AjaxPostResponse("no");
			return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
		}

		// 更新状态
		SqlFileList sqlFileList = new SqlFileList();
		FileListModel file = new FileListModel();
		file.setFileId(fileId);
		file.setStatus("Y");
		try {
			sqlFileList.updateDate(file);
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			LOG.info("文件状态改动成功:" + e1);
			e1.printStackTrace();
		}

		// LOG.info("00000"+classifyName);
		classifyName = classifyName.replace("-", "");
		// LOG.info(classifyName);

		// 加入数据
		SqlVideoList sqlvideo = new SqlVideoList();
		Date date = new Date();
		Timestamp timeStamp = new Timestamp(date.getTime());
		GetRandomString randomStr = new GetRandomString();
		for (int i = 0; i < urlList.size(); i++) {
			VideoListModel video = new VideoListModel();
			video.setUserId(userId);
			video.setUrl(urlList.get(i));// 视频源地址
			video.setTitle(titleList.get(i));// 视频标题

			String urlstr = urlList.get(i);
			// String path=urlstr.substring(0, urlstr.indexOf("?"));
			// String format=path.substring(path.lastIndexOf("."),
			// path.length());//视频格式
			// String baseName = FilenameUtils.getBaseName(urlstr);
			String extendname = FilenameUtils.getExtension(urlstr);
			if(extendname.contains("?

")){
				extendname=extendname.substring(0,extendname.indexOf("?

"));
			}

			if (StringUtils.isBlank(extendname)) {
				extendname = "mp4";
			}
			String trueName = randomStr.generateRandomString(15);
			String filename = trueName + "." + extendname;
			video.setTrueName(filename);// 用于下载使用的视频名称

			video.setClassifyId(classifyId);
			video.setClassifyName(classifyName.trim());
			video.setStatus(VideoStatus.NO.getValue());// 等待、
			video.setVid("");
			video.setCreateTime(timeStamp);

			try {
				sqlvideo.insertDate(video);// 加入数据库
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				LOG.info("加入数据库:" + e);
				e.printStackTrace();
				AjaxPostResponse resp = new AjaxPostResponse("no");
				return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
			}
		}

		AjaxPostResponse resp = new AjaxPostResponse("yes");
		return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
	}

	/**
	 * 获取下载进度
	 *
	 * @return
	 */
	@RequestMapping(value = "/grab/download/progress", method = { RequestMethod.POST,
			RequestMethod.GET })
	public ResponseEntity<AjaxPostResponse> getProgress(HttpServletRequest request,
			HttpServletResponse response) {
		Integer id = ServletRequestUtils.getIntParameter(request, "videoId", 0);
		String userId = ServletRequestUtils.getStringParameter(request, "userId", "test");
		String urlstr = ServletRequestUtils.getStringParameter(request, "url", "");
		String trueName = ServletRequestUtils.getStringParameter(request, "trueName", "");

		MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(mediaType);

		// LOG.info("--id---"+id+"---u---"+userId);

		int content = 1;
		int length = 1;
		int progress = 1;

		// LOG.info("-------ccccc4------------"+session.getAttribute("fileSize"+id));
		if (memcachedClient.get("fileSize" + String.valueOf(id)) == null) {
			// 文件大小还没存进session中
			List<TaskQueue> list = new ArrayList<TaskQueue>();
			SqlTaskQueue stq = new SqlTaskQueue();
			try {
				list = stq.selectDateOne(String.valueOf(id));
			} catch (SQLException e2) {
				// TODO Auto-generated catch block
				LOG.info("查询文件大小" + e2);
				e2.printStackTrace();
			}

			if (list.size() > 0) {
				TaskQueue tQueue = list.get(0);
				content = tQueue.getFileSize();
				memcachedClient.set("fileSize" + String.valueOf(id),24*60*60, content);// 存进session
			} else {
				URL url = null;
				try {
					url = new URL(urlstr);
					HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 进行连接握手
					connection.setRequestMethod("GET");// 请求方式
					content = (int) connection.getContentLength();
					memcachedClient.set("fileSize" + String.valueOf(id),24*60*60,content);//memcached
					// LOG.info("-------content------"+content);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					LOG.info("链接失败" + e1);
					e1.printStackTrace();
				}
			}
		} else {
			// 文件大少在session中
			String contentString = String.valueOf(memcachedClient.get("fileSize"
					+ String.valueOf(id)));
			// LOG.info("-------ccccc------------"+contentString);
			content = Integer.parseInt(contentString.trim());
		}

		// 文件存储位置、文件命名处理
		try {
			// String path=urlstr.substring(0, urlstr.indexOf("?"));
			// String name=path.substring(path.lastIndexOf("/")+1,
			// path.length());
			// String filename=name.trim();
			String filename = trueName;

			File file = new File(filePath, filename);

			if (!file.exists()) {
				progress = (Integer) memcachedClient.get(userId + id);// 将当前下载进度存放到session中。
			} else {
				length = (int) file.length();
				progress = length * 100 / content;
				// 将当前下载进度存放到session中。
				memcachedClient.set(userId + id,24*60*60,progress);
				LOG.info(id + "-------progress------" + progress);
			}

		} catch (Exception e) {
			LOG.info("不能解析的路径:" + e);
			AjaxPostResponse resp = new AjaxPostResponse(progress);
			return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
		}

		AjaxPostResponse resp = new AjaxPostResponse(progress);
		return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
	}

	/**
	 * 批量抓取视频(下载视频模块--依据视频源地址去抓取视频)管理
	 *
	 * @return
	 * @throws MalformedURLException
	 */
	@RequestMapping(value = "/grab/download/manage", method = { RequestMethod.POST })
	public ModelAndView grabDownloadVideo(HttpServletRequest request, HttpServletResponse response) {
		int[] id = ServletRequestUtils.getIntParameters(request, "videoId");
		String userId = ServletRequestUtils.getStringParameter(request, "userId", "test");
		String[] urlstr = ServletRequestUtils.getStringParameters(request, "url");
		String[] trueName = ServletRequestUtils.getStringParameters(request, "trueName");

		int len = id.length;

		List<TaskQueue> taskQueues = new ArrayList<TaskQueue>();
		for (int i = 0; i < len; i++) {
			TaskQueue tq = new TaskQueue();
			tq.setTaskId(String.valueOf(id[i]));
			tq.setVideoId(id[i]);
			tq.setUserId(userId);
			tq.setVideoUrl(urlstr[i]);
			tq.setTrueName(trueName[i]);
			taskQueues.add(tq);
		}

		SqlTaskQueue stq = new SqlTaskQueue();
		SqlVideoList svl = new SqlVideoList();

		// 把任务队列加入进数据库
		if (taskQueues.size() > 0) {
			// 存在有任务
			for (int i = 0; i < taskQueues.size(); i++) {
				TaskQueue task = taskQueues.get(i);
				List<TaskQueue> taskList = new ArrayList<TaskQueue>();// 查询任务是否已存在
				try {
					taskList = stq.selectDateOne(task.getTaskId());
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				if (taskList.size() > 0) {
					// 该任务已存在
				} else {
					task.setFileSize(0);
					task.setProgress(0);
					task.setStatus("N");
					Date date = new Date();
					Timestamp timeStamp = new Timestamp(date.getTime());
					task.setCreateTime(timeStamp);
					try {
						stq.insertDate(task);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						LOG.info("下载任务加入失败!" + e);
						e.printStackTrace();
					}
				}
			}
		}

		// 获取全部的任务队列
		List<TaskQueue> workQueues = new ArrayList<TaskQueue>();
		try {
			workQueues = stq.selectDate(userId);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			LOG.info("获取下载任务失败" + e);
			e.printStackTrace();
		}
		// ExecutorService pool = Executors.newFixedThreadPool(3);
		if (workQueues.size() > 0) {
			for (int i = 0; i < workQueues.size(); i++) {
				String taskId = workQueues.get(i).getTaskId();
				String urltxt = workQueues.get(i).getVideoUrl();
				String filename = workQueues.get(i).getTrueName();

				File saveFile = new File(filePath, filename);// 文件保存的位置
				File fileDir = new File(filePath);
				if (!fileDir.exists()) {
					fileDir.mkdirs();// 文件夹不存在创建文件夹
				}
				URL url = null;
				try {
					url = new URL(workQueues.get(i).getVideoUrl());
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					LOG.info("握手失败" + e);
					e.printStackTrace();
				}

				if (url != null) {
					// 将下载任务线程,放入线程池中运行
					ExecutorService executor = (ExecutorService) context
							.getAttribute("DOWNLOAD_EXECUTOR");
					executor.submit(new DownloadVideo(url, saveFile, taskId));
					// pool.execute(new
					// DownloadVideo(url,saveFile,taskId));////////////////////////////////////
					VideoListModel vlm = new VideoListModel();
					vlm.setId(workQueues.get(i).getVideoId());
					vlm.setUserId(userId);
					vlm.setStatus(VideoStatus.WAIT.getValue());// 将状态改为等待
					try {
						svl.updateDate(vlm);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						LOG.info("更改下载状态失败" + e);
						e.printStackTrace();
					}

				}
			}
		}
		// 关闭线程池
		// pool.shutdown();

		// 又一次查询视频列表
		List<VideoListModel> list = new ArrayList<VideoListModel>();
		try {
			list = svl.selectDate(userId);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ModelAndView mav = new ModelAndView();
		mav.addObject("videolist", list);
		mav.addObject("userId", userId);
		mav.setViewName("video/download");
		return mav;

	}

	/**
	 * 获取视频的下载进度()
	 * @param request
	 */
	@RequestMapping(value="/grab/download/status",method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody
	ResponseEntity<String> downloadStatus(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		String userId = null;
		if (memcachedClient.get("userId") != null) {
			userId = (String) memcachedClient.get("userId");
			SqlVideoList sqlVideoList = new SqlVideoList();
			List<VideoListModel> list = new ArrayList<VideoListModel>();
			try {
				list = sqlVideoList.selectDate(userId);
				for (int i = 0; i < list.size(); i++) {
					VideoListModel model = list.get(i);

					String filename = model.getTrueName();
					File file = new File(filePath, filename);

					if (file.exists()) {

						int downloaded = (int) file.length();
						if (model.getFileSize() != 0) {
							System.out.println(model.getId()+"===n==="+model.getTrueName()+"===d==="+downloaded+"===s==="+model.getFileSize()+"===="+(long)downloaded * 100 /(long) model.getFileSize());
							model.setPercent((int) ((long)downloaded * 100 /(long) model.getFileSize()));
						} 

					}

				}
				ObjectMapper objectMapper = new ObjectMapper();
				String result = objectMapper.writeValueAsString(list);

				MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
				HttpHeaders headers = new HttpHeaders();
				headers.setContentType(mediaType);
				return new ResponseEntity<String>(result, headers, HttpStatus.OK);

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return null;

	}

	@RequestMapping(value = "/grab/download/manage", method = { RequestMethod.GET })
	public ModelAndView grabVideo(HttpServletRequest request, HttpServletResponse response) {
		// String userId = ServletRequestUtils.getStringParameter(request,
		// "userId", "");
		String userId = null;

		ModelAndView mav = new ModelAndView();

		if (memcachedClient.get("userId") != null) {
			userId = (String) memcachedClient.get("userId");
			SqlVideoList sqlVideoList = new SqlVideoList();
			List<VideoListModel> list = new ArrayList<VideoListModel>();
			try {
				list = sqlVideoList.selectDate(userId);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mav.addObject("videolist", list);
			mav.addObject("userId", userId);
			mav.setViewName("video/download");
			return mav;
		}

		mav.setViewName("video/login");
		return mav;
	}

	/**
	 * 导出下载成功的视频
	 *
	 * @return
	 */
	@RequestMapping(value = "/grab/export", method = { RequestMethod.GET })
	public ModelAndView exportVideo(HttpServletRequest request, HttpServletResponse response) {
		// String userId = ServletRequestUtils.getStringParameter(request,
		// "userId", "");
		String userId = null;
		ModelAndView mav = new ModelAndView();

		if (memcachedClient.get("userId") != null) {
			userId = (String) memcachedClient.get("userId");
			SqlVideoList sqlVideoList = new SqlVideoList();
			List<VideoListModel> list = new ArrayList<VideoListModel>();
			try {
				list = sqlVideoList.selectSuccessDate(userId);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mav.addObject("videolist", list);
			mav.addObject("userId", userId);
			mav.setViewName("video/export");
			return mav;
		}

		mav.setViewName("video/login");
		return mav;
	}

	/**
	 * export导出文件
	 */
	@RequestMapping(value = "/grab/export/csv", method = { RequestMethod.GET })
	public void exportCsv(HttpServletRequest request, HttpServletResponse response) {
		String userId = ServletRequestUtils.getStringParameter(request, "userId", "");

		if (StringUtils.isNotBlank(userId)) {

			SqlVideoList sqlVideoList = new SqlVideoList();
			List<VideoListModel> list = new ArrayList<VideoListModel>();
			try {
				list = sqlVideoList.selectSuccessDate(userId);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// 导出txt文件
			response.setContentType("text/plain");
			String fileName = "videolist";
			try {
				fileName = URLEncoder.encode("videolist", "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
			BufferedOutputStream buff = null;
			StringBuffer write = new StringBuffer();
			String enter = "\r\n";
			ServletOutputStream outSTr = null;
			try {
				outSTr = response.getOutputStream(); // 建立
				buff = new BufferedOutputStream(outSTr);
				// 把内容写入文件
				if (list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						write.append(list.get(i).getUrl());
						write.append(",");
						write.append(list.get(i).getTitle());
						write.append(",");
						write.append(list.get(i).getVid());
						write.append(enter);
					}
				}
				buff.write(write.toString().getBytes("UTF-8"));
				buff.flush();
				buff.close();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					buff.close();
					outSTr.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 清空导出视频列表
	 * /grab/export/clean
	 */
	@RequestMapping(value = "/grab/export/clean", method = { RequestMethod.GET })
	public ResponseEntity<AjaxPostResponse> cleanVideo(HttpServletRequest request,
			HttpServletResponse response) {

		MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(mediaType);

		if (memcachedClient.get("userId") != null) {
			String userId=(String) memcachedClient.get("userId");
			SqlVideoList sqlVideoList=new SqlVideoList();
			try {
				sqlVideoList.cleanDate(userId);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			//删除成功
			System.out.println("删除成功!");
			AjaxPostResponse resp = new AjaxPostResponse("yes");
			return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
		}else{
			//删除失败
			System.out.println("删除失败!");
			AjaxPostResponse resp = new AjaxPostResponse("no");
			return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
		}

	}

	/**
	 * 删除视频
	 * /grab/export/clean
	 */
	@RequestMapping(value = "/grab/delete/videoId", method = { RequestMethod.GET })
	public ResponseEntity<AjaxPostResponse> deleteVideo(HttpServletRequest request,
			HttpServletResponse response) {
		String videoId = ServletRequestUtils.getStringParameter(request, "videoId", null);

		MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(mediaType);

		if (StringUtils.isNotBlank(videoId)) {
			SqlTaskQueue stq=new SqlTaskQueue();
			SqlVideoList sqlVideoList=new SqlVideoList();
			try {
				List<TaskQueue> list=stq.selectDateOne(videoId);
				if(list.size()>0){
					stq.deleteDate(videoId);//删除任务
				}
				sqlVideoList.deleteDate(videoId);//删除视频
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				System.out.println("删除失败"+e);
				e.printStackTrace();
			}

			//删除成功
			AjaxPostResponse resp = new AjaxPostResponse("yes");
			return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
		}else{
			//删除失败
			AjaxPostResponse resp = new AjaxPostResponse("no");
			return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
		}

	}

}
时间: 2024-10-22 11:39:01

Spting使用memcached的相关文章

关于win下Memcached安装步骤

2天对我来说有点煎熬..数据量达到17w的时候 我本地执行查询速度特别慢! 请教了一些php大牛如何解决速度问题,在加了索引和优化sql后还是速度慢!我决定在win环境下用Memcached和memcache 来处理,先声明一下: memcache是php的拓展,memcached是客户端,复杂的说:Memcache模块提供了于memcached方便的面向过程及面向对象的接口,memcached是为了降低动态web应用 从数据库加载数据而产生的一种常驻进程缓存产品. 因为我本地用的是xampp集

memcached安装

今天有台服务器需要迁移业务安装memcached,以前没有安装过,按照网上步骤尝试了下,并且记录了安装过程. 安装包准备: libevent-1.4.14b-stable.tar.gz memcached-1.4.5.tar.gz 首先安装libevent: tar zxvf libevent-1.4.14-stable.tar.gz -C /usr/local/ cd libevent-1.4.14-stable/ ./configure -prefix=/usr/libevent make

Linux下安装搭建Memcached集群环境

Linux下安装搭建Memcached集群环境

linux编译安装memcached

Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载. 它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度. Memcached基于一个存储键/值对的hashmap.其守护进程(daemon )是用C写的,但是客户端可以 用任何语言来编写,并通过memcached协议与守护进程通信. 1.memcached安装: 安装开发包:yum -y install gcc 安装memcached相应依赖组件: yum -y ins

(apache+tomcat集群+memcached番外篇)单台tomcat的session信息的2种持久化方式

为什么要实现搭建tomcat集群环境呢?主要因为单个tomcat无论从吞吐量和并发数上,会达到一定的极限.如果访问量超过单个tomcat的承受能力的话,tomcat一般要么拒绝提供服务,要么直接宕掉.所以,必须要依靠tomcat集群技术.举个最简单的例子,拿"送快件"比喻,如果一个人,5分钟送一件,一小时之内,送10个,一个人完全能胜任这项工作.假设现在到了双十一,要求1小时,送100个, 那怎么办?只能安排更多的人加入"送快件"这项工作中来.这其实和集群一个道理.

修改memcached服务的端口号

windows下修改memcached服务的端口号(默认端口:11211) 如果不是作为服务启动memcached的话,memcached -p 端口号就可以了. 通过修改注册表可以简单实现 运行:regedit打开注册表,搜索memcached或者按下面的目录查找: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\memcached Server 其中的ImagePath项的值为:"c:\memcached\memcached.exe&

基于nginx+tomcat的负载均衡以及memcached解决交叉存储

nginx是以多进程的方式工作的,有一个master进程和多个worker进程master进程用来管理worker进程(1)向各worker进程发送信号(2)监控worker进程,当一个worker进程出现异常后,会启动新的worker进程. master进程会先建立好需要监听的socket,fork函数生成子进程workers,继承scoket,一般来讲,当有连接进入后,所有accept在这个socket上面的进程都会收到通知,而只有一个进程会accept这个连接,其它都会失败.  --->

第八章 企业项目开发--分布式缓存memcached

注意:本节代码基于<第七章 企业项目开发--本地缓存guava cache> 1.本地缓存的问题 本地缓存速度一开始高于分布式缓存,但是随着其缓存数量的增加,所占内存越来越大,系统运行内存越来越小,最后系统会被拖慢(这一点与第二点联系起来) 本地缓存存于本机,其缓存数量与大小受本机内存大小限制 本地缓存存于本机,其他机器的访问不到这样的缓存 解决方案:分布式缓存 Jboss cache:缓存还存于本机,但是会同步更新到其他机器(解决了第三个问题,解决不了第一和第二个问题),如果缓存机器数量很多

memcached完全剖析–1. memcached的基础

系列文章导航: memcached完全剖析–1. memcached的基础 memcached全面剖析–2. 理解memcached的内存存储 memcached全面剖析–3. memcached的删除机制和发展方向 memcached全面剖析–4. memcached的分布式算法 memcached全面剖析–5. memcached的应用和兼容程序 翻译一篇技术评论社的文章,是讲memcached的连载.fcicq同学说这个东西很有用,希望大家喜欢. 发表日:2008/7/2 作者:长野雅广(