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);
} } }
Spting使用memcached的更多相关文章
- 支持 .NET Core 的 Memcached 客户端 EnyimMemcachedCore
1. 介绍 EnyimMemcachedCore 是一个支持 .NET Core 的 Memcached 客户端,是从 EnyimMemcached 迁移至 .NET Core的,源代码托管在 Git ...
- Key/Value之王Memcached初探:二、Memcached在.Net中的基本操作
一.Memcached ClientLib For .Net 首先,不得不说,许多语言都实现了连接Memcached的客户端,其中以Perl.PHP为主. 仅仅memcached网站上列出的语言就有: ...
- ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存
ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存 part 1:给我点时间,允许我感慨一下2016年 正好有时间,总结一下最近使用的一些技术,也算是为2016年画上一个完 ...
- 缓存、队列(Memcached、redis、RabbitMQ)
本章内容: Memcached 简介.安装.使用 Python 操作 Memcached 天生支持集群 redis 简介.安装.使用.实例 Python 操作 Redis String.Hash.Li ...
- 企业做数据缓存是使用Memcached还是选Redis?
企业是使用Memcached还是选Redis? 在构建一款现代且由数据库驱动的Web应用程序并希望使其拥有更为出色的性能表现时,这个问题总会时不时出现.并给每一位开发人员带来困扰.在考虑对应用程序的性 ...
- NoSql1 在Linux(CentOS)上安装memcached及使用
前言: 今天是初五,生活基本要从过年的节奏中回归到正常的生活了,所以想想也该想想与工作有关的事情了.我之前在工作中会经常使用memcached和redis,但是自己一直没有时间系统的好好看 ...
- Memcached简介
在Web服务开发中,服务端缓存是服务实现中所常常采用的一种提高服务性能的方法.其通过记录某部分计算结果来尝试避免再次执行得到该结果所需要的复杂计算,从而提高了服务的运行效率. 除了能够提高服务的运行效 ...
- Linux 服务器 安装 memcached
linux centos 一.memcached的安装 1.下载 memcached-1.4.33.tar.gz.libevent-2.0.22-stable.tar.gz 安装 memcached ...
- Memcached和Redis比较
一.存储 Memcached基本只支持简单的key-value存储方式.Redis除key-value之外,还支持list,set,sorted set,hash等数据结构:Redis支持数据的备份, ...
随机推荐
- Android硬件抽象层(HAL)概要介绍和学习计划
文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6567257 Android的硬件抽象层,简单来 ...
- oracle函数Lpad与Rpad
函数介绍 lpad函数从左边对字符串使用指定的字符进行填充.从其字面意思也可以理解,l是left的简写,pad是填充的意思,所以lpad就是从左边填充的意思. 语法格式如下: lpad( string ...
- T-SQL和PL/SQL 区别
结构化查询语言(Structured Query Language)简称SQL,是一种特殊目的的编程语言,是一种数据库查询和程序设计语言,用于存取数据以及查询.更新和管理关系数据库系统:同时也是数据库 ...
- js静态方法
1.ajax() 方法是属于“函数”本身的,和返回的对象没有关系 2.bark药调用,必须药new Hashiqi()得到对象,且由返回对象才能调用 3.ajax()方法药调用,不需要new对象,直接 ...
- SSH连接LINUX乱码解决方法
1.vi /etc/sysconfig/i18n 将内容改为 LANG="zh_CN.GB18030" LANGUAGE="zh_CN.GB18030:zh_CN.GB2 ...
- No redirect found in host configuration file (C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet.config).
Configuration Error Description: An error occurred during the processing of a configuration file req ...
- /调整button的title的位置
[bottomButton setTitleEdgeInsets:UIEdgeInsetsMake(10, -190, 10, 44)]; //上左下右 ||button.co ...
- (转) launch failed.Binary not found in Linux/Ubuntu解决方案
原地址: http://blog.csdn.net/abcjennifer/article/details/7573916 Linux下出现launch failed.Binary not found ...
- CDZSC_2015寒假新人(1)——基础 g
Description Ignatius likes to write words in reverse way. Given a single line of text which is writt ...
- PHP图片加文字水印和图片水印方法
文字水印 $dst_path = 'dst.jpg'; //创建图片的实例$dst = imagecreatefromstring(file_get_contents($dst_path)); //打 ...