Spring使用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" />   
                
    </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);   
}   
}   
}  

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/8017.html

(0)
上一篇 2021年7月18日
下一篇 2021年7月18日

相关推荐

发表回复

登录后才能评论