当前位置: 首页 > news >正文

好的兼职做调查网站甘肃省住房城乡建设厅网站首页

好的兼职做调查网站,甘肃省住房城乡建设厅网站首页,教做宝宝衣服的网站,绥化市建设工程网站招投标目录 1.将文件上传至云服务器 1.1 处理上传头像逻辑 1.1.1 客户端上传 1.1.2 服务器直传 2.优化网站的性能 2.1 本地缓存优化查询方法 2.2 压力测试 1.将文件上传至云服务器 客户端上传#xff1a;客户端将数据提交给云服务器#xff0c;并等待其响应#xff1b;用户…目录 1.将文件上传至云服务器 1.1 处理上传头像逻辑 1.1.1 客户端上传 1.1.2 服务器直传 2.优化网站的性能 2.1 本地缓存优化查询方法 2.2 压力测试 1.将文件上传至云服务器 客户端上传客户端将数据提交给云服务器并等待其响应用户上传头像时将表单数据提交给服务器服务器直传应用服务器将数据直接提交给云服务器并等待其响应分享时服务端将自动生成的图片直接提交给云服务器 使用七牛云服务器 导入依赖 !-- https://mvnrepository.com/artifact/com.qiniu/qiniu-java-sdk -- dependencygroupIdcom.qiniu/groupIdartifactIdqiniu-java-sdk/artifactIdversion7.12.1/version /dependency在 application.properties 中配置 # qiniu qiniu.key.accessNHzlA2MRle10vB0wNeO54aGS-tMjEpO5BiIrflz9 qiniu.key.secretqicgWpPOslm5_dFu_j_94r5gUcKm_UekhT2MMLPf qiniu.bucket.header.namecommunityheader123321 quniu.bucket.header.urlhttp://s6sc3za8f.hb-bkt.clouddn.com qiniu.bucket.share.namecommunityshare123321 qiniu.bucket.share.urlhttp://s6scgzhqs.hb-bkt.clouddn.com 1.1 处理上传头像逻辑 1.1.1 客户端上传 打开 UserController 类 注入上述的两个 key注入有关头像的空间内容废弃原来上传头像方法上传头像因为有表单所以在客户端上传表单直接提交给七牛云废弃此方法上传文件同样废弃在打开用户设置的页面时需要生成凭证设置上传文件名称响应信息将凭证写到表单中当打开表单时表单中应该有凭证最后传给模板还需要添加一个方法在表单中将数据提交给七牛云七牛云返回一个消息然后将 User 表中的 headurl 做一个更新更新为七牛云的路径 Value(${qiniu.key.access})private String accessKey;Value(${qiniu.key.secret})private String secretKey;Value(${qiniu.bucket.header.name})private String headerBucketName;Value(${quniu.bucket.header.url})private String headerBucketUrl;LoginRequiredRequestMapping(path /setting, method RequestMethod.GET)//添加方法使得浏览器通过方法访问到设置的页面public String getSettingPage(Model model) {// 上传文件名称String fileName CommunityUtil.generateUUID();// 设置响应信息StringMap policy new StringMap();policy.put(returnBody, CommunityUtil.getJSONString(0));// 生成上传凭证Auth auth Auth.create(accessKey, secretKey);String uploadToken auth.uploadToken(headerBucketName, fileName, 3600, policy);model.addAttribute(uploadToken, uploadToken);model.addAttribute(fileName, fileName);return /site/setting;}// 更新头像路径RequestMapping(path /header/url, method RequestMethod.POST)ResponseBodypublic String updateHeaderUrl(String fileName) {if (StringUtils.isBlank(fileName)) {return CommunityUtil.getJSONString(1, 文件名不能为空!);}String url headerBucketUrl / fileName;userService.updateHeader(hostHolder.getUser().getId(), url);return CommunityUtil.getJSONString(0);} 再处理表单 setting.html !-- 上传头像 --h6 classtext-left text-info border-bottom pb-2上传头像/h6!--上传到本地--!--form classmt-5 methodpost enctypemultipart/form-data th:action{/user/upload}div classform-group row mt-4label forhead-image classcol-sm-2 col-form-label text-right选择头像:/labeldiv classcol-sm-10div classcustom-fileinput typefile th:class|custom-file-input ${error!null?is-invalid:}|idhead-image nameheaderImage langes requiredlabel classcustom-file-label forhead-image data-browse文件选择一张图片/labeldiv classinvalid-feedback th:text${error}该账号不存在!/div/div/div/divdiv classform-group row mt-4div classcol-sm-2/divdiv classcol-sm-10 text-centerbutton typesubmit classbtn btn-info text-white form-control立即上传/button/div/div/form--!--上传到七牛云--form classmt-5 iduploadFormdiv classform-group row mt-4label forhead-image classcol-sm-2 col-form-label text-right选择头像:/labeldiv classcol-sm-10div classcustom-fileinput typehidden nametoken th:value${uploadToken}input typehidden namekey th:value${fileName}input typefile classcustom-file-input idhead-image namefile langes requiredlabel classcustom-file-label forhead-image data-browse文件选择一张图片/labeldiv classinvalid-feedback该账号不存在!/div/div/div/divdiv classform-group row mt-4div classcol-sm-2/divdiv classcol-sm-10 text-centerbutton typesubmit classbtn btn-info text-white form-control立即上传/button/div/div/form 在 static 包下 js 包新建 setting.js  $(function(){$(#uploadForm).submit(upload); });function upload() {$.ajax({url: http://upload-z1.qiniup.com,method: post,processData: false,contentType: false,data: new FormData($(#uploadForm)[0]),success: function(data) {if(data data.code 0) {// 更新头像访问路径$.post(CONTEXT_PATH /user/header/url,{fileName:$(input[namekey]).val()},function(data) {data $.parseJSON(data);if(data.code 0) {window.location.reload();} else {alert(data.msg);}});} else {alert(上传失败!);}}});return false; } 1.1.2 服务器直传 需要重构分享相关的功能打开 ShareController 注入分享空间的 url修改返回浏览器的路径七牛云空间路径 空间 url / 图片名字废弃从本地获取图片传给客户端的方法传给七牛云之后通过七牛云获取图片 Value(${qiniu.bucket.share.url})private String shareBucketUrl;RequestMapping(path /share, method RequestMethod.GET)ResponseBodypublic String share(String htmlUrl) {// 文件名String fileName CommunityUtil.generateUUID();// 异步生成长图Event event new Event().setTopic(TOPIC_SHARE).setData(htmlUrl, htmlUrl).setData(fileName, fileName).setData(suffix, .png);//触发事件eventProducer.fireEvent(event);// 返回访问路径MapString, Object map new HashMap();// map.put(shareUrl, domain contextPath /share/image/ fileName);map.put(shareUrl, shareBucketUrl / fileName);return CommunityUtil.getJSONString(0, null, map);}// 废弃// 获取长图RequestMapping(path /share/image/{fileName}, method RequestMethod.GET)public void getShareImage(PathVariable(fileName) String fileName, HttpServletResponse response) {if (StringUtils.isBlank(fileName)) {throw new IllegalArgumentException(文件名不能为空!);}response.setContentType(image/png);File file new File(wkImageStorage / fileName .png);try {OutputStream os response.getOutputStream();FileInputStream fis new FileInputStream(file);byte[] buffer new byte[1024];int b 0;while ((b fis.read(buffer)) ! -1) {os.write(buffer, 0, b);}} catch (IOException e) {logger.error(获取长图失败: e.getMessage());}}修改 EventConsumer逻辑是在消费者中体现 在消费者中消费事件传入两个 key 和上传空间的 name注入 ThreadPoolTaskScheduler在消费分享事件中在执行生成图片时启用定时器监视该图片一旦生成则上传至七牛云. // 消费分享事件KafkaListener(topics TOPIC_SHARE)public void handleShareMessage(ConsumerRecord record) {if (record null || record.value() null) {logger.error(消息的内容为空!);return;}Event event JSONObject.parseObject(record.value().toString(), Event.class);if (event null) {logger.error(消息格式错误!);return;}//获取 html、文件名、后缀String htmlUrl (String) event.getData().get(htmlUrl);String fileName (String) event.getData().get(fileName);String suffix (String) event.getData().get(suffix);//拼接参数String cmd wkImageCommand --quality 75 htmlUrl wkImageStorage / fileName suffix;//执行命令try {Runtime.getRuntime().exec(cmd);logger.info(生成长图成功: cmd);} catch (IOException e) {logger.error(生成长图失败: e.getMessage());}// 启用定时器,监视该图片,一旦生成了,则上传至七牛云.UploadTask task new UploadTask(fileName, suffix);//触发定时器执行Future future taskScheduler.scheduleAtFixedRate(task, 500);//完成任务后定时器关闭task.setFuture(future);}//相当于线程体class UploadTask implements Runnable {// 文件名称private String fileName;// 文件后缀private String suffix;// 启动任务的返回值private Future future;// 开始时间private long startTime;// 上传次数private int uploadTimes;public UploadTask(String fileName, String suffix) {this.fileName fileName;this.suffix suffix;this.startTime System.currentTimeMillis();}public void setFuture(Future future) {this.future future;}Overridepublic void run() {// 生成失败if (System.currentTimeMillis() - startTime 30000) {logger.error(执行时间过长,终止任务: fileName);future.cancel(true);return;}// 上传失败if (uploadTimes 3) {logger.error(上传次数过多,终止任务: fileName);future.cancel(true);return;}//没有上述情况继续执行相关逻辑//从本地中寻找文件String path wkImageStorage / fileName suffix;//本地路径File file new File(path);if (file.exists()) {logger.info(String.format(开始第%d次上传[%s]., uploadTimes, fileName));// 设置响应信息StringMap policy new StringMap();// 成功返回0policy.put(returnBody, CommunityUtil.getJSONString(0));// 生成上传凭证Auth auth Auth.create(accessKey, secretKey);String uploadToken auth.uploadToken(shareBucketName, fileName, 3600, policy);// 指定上传机房UploadManager manager new UploadManager(new Configuration(Zone.zone1()));try {// 开始上传图片Response response manager.put(path, fileName, uploadToken, null, image/ suffix, false);// 处理响应结果JSONObject json JSONObject.parseObject(response.bodyString());if (json null || json.get(code) null || !json.get(code).toString().equals(0)) {logger.info(String.format(第%d次上传失败[%s]., uploadTimes, fileName));} else {logger.info(String.format(第%d次上传成功[%s]., uploadTimes, fileName));future.cancel(true);}} catch (QiniuException e) {logger.info(String.format(第%d次上传失败[%s]., uploadTimes, fileName));}} else {logger.info(等待图片生成[ fileName ].);}}} 2.优化网站的性能 本地缓存将数据缓存在应用服务器上性能最好常用的缓存工具Ehcache、Guava、Caffeine等 分布式缓存将数据缓存在 NoSQL 数据库上跨服务器常用缓存工具MemCache、Redis等 多级缓存一级缓存 二级缓存 DB避免缓存雪崩缓存失效大量请求直达DB提高系统的可用性 2.1 本地缓存优化查询方法 本地缓存主要使用 Caffeine 工具导入依赖 dependencygroupIdcom.github.ben-manes.caffeine/groupIdartifactIdcaffeine/artifactIdversion2.7.0/version/dependency 设置自定义参数 # caffeine caffeine.posts.max-size15 caffeine.posts.expire-seconds180 优化查询方法discussPostService 初始化 Logger记录日志注入上述申明参数Caffeine核心接口: Cache, LoadingCache同步缓存多个线程同时访问缓存中的数据但是缓存中没有数据让多个线程排队等待然后缓存去数据库中取, AsyncLoadingCache异步缓存支持并发同时取数据声明帖子列表缓存使用 LoadingCacheString, ListDiscussPost使用 key 缓存 value声明帖子总数缓存使用 LoadingCacheInteger, Integer在服务启动或者首次调用 DiscussPostService初始化一次上述两个缓存即可给当前类新增初始化方法添加注解 PostConstruct初始化帖子列表缓存和帖子总数缓存在查询某一页的方法中需要启动缓存的条件缓存热门帖子orderMode 1并且缓存首页访问首页的时候userId 是不传为0缓存的是一页的数据key 为 offset 和 limit 组合否则访问数据库在访问之前记录一下日志load post list from DB.在查询总数的方法中用户查看自己帖子的时候不需要缓存但是当 userId 0 为首页查询需要缓存帖子总数 private static final Logger logger LoggerFactory.getLogger(DiscussPostService.class);Value(${caffeine.posts.max-size})private int maxSize;Value(${caffeine.posts.expire-seconds})private int expireSeconds;// Caffeine核心接口: Cache, LoadingCache, AsyncLoadingCache// 帖子列表缓存private LoadingCacheString, ListDiscussPost postListCache;// 帖子总数缓存private LoadingCacheInteger, Integer postRowsCache;PostConstructpublic void init() {// 初始化帖子列表缓存postListCache Caffeine.newBuilder().maximumSize(maxSize)//缓存最大数据量.expireAfterWrite(expireSeconds, TimeUnit.SECONDS)//把缓存写入缓存空间多长时间自动过期.build(new CacheLoaderString, ListDiscussPost() {//当尝试从缓存中取数据caffeine会看缓存是否有数据//没有需要提供一个查询的方法load就是实现这个查询方法NullableOverridepublic ListDiscussPost load(NonNull String key) throws Exception {//实现访问数据库查数据if (key null || key.length() 0) {throw new IllegalArgumentException(参数错误!);}//不为空解析 keyoffset : limit进行切割String[] params key.split(:);if (params null || params.length ! 2) {throw new IllegalArgumentException(参数错误!);}int offset Integer.valueOf(params[0]);int limit Integer.valueOf(params[1]);// 二级缓存: Redis - mysqllogger.debug(load post list from DB.);//调用discussPostMapper查询数据userId 0 orderMode 1return discussPostMapper.selectDiscussPosts(0, offset, limit, 1);}});// 初始化帖子总数缓存postRowsCache Caffeine.newBuilder().maximumSize(maxSize).expireAfterWrite(expireSeconds, TimeUnit.SECONDS).build(new CacheLoaderInteger, Integer() {NullableOverridepublic Integer load(NonNull Integer key) throws Exception {logger.debug(load post rows from DB.);return discussPostMapper.selectDiscussPostRows(key);}});}//声明一个业务方法查询某一页的方法返回类型是集合public ListDiscussPost findDiscussPosts(int userId, int offset, int limit, int orderMode) {//缓存热门帖子orderMode 1并且缓存首页访问首页的时候userId 是不传为0// 缓存的是一页的数据key 为 offset 和 limit 组合if (userId 0 orderMode 1) {return postListCache.get(offset : limit);}//否则访问数据库在访问之前记录一下日志logger.debug(load post list from DB.);return discussPostMapper.selectDiscussPosts(userId, offset, limit, orderMode);}//查询行数的方法public int findDiscussPostRows(int userId) {if (userId 0) {return postRowsCache.get(userId);}logger.debug(load post rows from DB.);return discussPostMapper.selectDiscussPostRows(userId);}测试类 package com.example.demo;import com.example.demo.entity.DiscussPost; import com.example.demo.service.DiscussPostService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner;import java.util.Date;RunWith(SpringRunner.class) SpringBootTest ContextConfiguration(classes DemoApplication.class) public class CaffeineTests {Autowiredprivate DiscussPostService postService;Testpublic void initDataForTest() {for (int i 0; i 300000; i) {DiscussPost post new DiscussPost();post.setUserId(111);post.setTitle(互联网求职暖春计划);post.setContent(今年的就业形势确实不容乐观);post.setCreateTime(new Date());post.setScore(Math.random() * 2000);postService.addDiscussPost(post);}}Testpublic void testCache() {System.out.println(postService.findDiscussPosts(0, 0, 10, 1));System.out.println(postService.findDiscussPosts(0, 0, 10, 1));System.out.println(postService.findDiscussPosts(0, 0, 10, 1));System.out.println(postService.findDiscussPosts(0, 0, 10, 0));}} 2.2 压力测试 使用 jmeter 工具测试 未添加缓存 添加缓存
http://www.w-s-a.com/news/888613/

相关文章:

  • 地方门户网站制作一级做c爱片的网站
  • 自己上传图片做动漫图网站北京福田汽车
  • 一级a做爰片免费网站录像ps做网站图片水印
  • 网页广告投放成都优化推广公司
  • 网站开发 印花税网页制作站点
  • 创建个人网站有什么好处国外建站系统
  • 桂林学校网站制作2018年网站设计公司
  • 建网站不想用怎样撤销搜狗收录提交入口网址
  • 做简单网站需要学什么软件有哪些南通优普网站建设
  • 网站排版尺寸湖北交投建设集团集团网站
  • 南京网站设计公司有哪些公司看动漫是怎么做视频网站
  • vs做网站怎么做窗体怎么在电脑上自己做网站吗
  • 做网站应该学什么网站编程 外包类型
  • 双鱼儿 网站建设站群系统哪个好用
  • 怎样自己做刷赞网站电商设计需要学什么软件有哪些
  • 关注城市建设网站居众装饰
  • 网站建设的语言优化企业网站
  • 成都旅游网站建设规划女性门户资讯类网站织梦dedecms模板
  • 二手车为什么做网站网站建设合作合同范文
  • 网站建设维护和网页设计做网站都需要服务器吗
  • 成都网站设计报告书系统平台
  • 怎样进行网站推广wordpress微博图床
  • 做一个平台 网站服务器搭建网架公司股价
  • 链家在线网站是哪个公司做的一个虚拟主机做2个网站
  • 网站开发实训报告模板学校网站建设计划
  • 免费手机网站制作方法什么事网站开发
  • 我们的爱情网站制作阿里云wordpress配置
  • 电脑网站页面怎么调大小唐山网站建设技术外包
  • 科威网络做网站怎么样wordpress分页样式
  • 泰安公司网站建设自助建站程序