页面优化技术

StringBuffer(f安) :线程安全的原因是在所有的方法上都加了Synchronized关键字。
但是为什么会有StringBuilder类:因为f安使用了Synchronized关键字,保证同一个时间
只有一个线程可以调用,所以有性能损耗,在一个方法内部定义局部变量属于堆栈封闭,只有单个线程可以访问,所以不用StringBuffer关键字的对象。

SimpleDateFormat:非线程安全的,如果多个线程来使用的话就会出错。可以用堆栈封闭的方法,每次都在方法内部new SimDateFormat。另外可以使用jodaTime里的DateTimeFormatter,这个是线程安全的。

同步容器:
ArrayList、HashMap、HashSet等Collections,一般我们都定义为私有变量,但是假如我们定义为static,多个线程去操作的时候就有可能引发异常。
线程安全类:
ArrayList -- > Vector、Stack
HashMap -- >HashTable(key value 不能为null)
另外就是Collections提供的方法,Collections.synchronizedXXX(List、Set、Map)

并发容器(J.U.C,java.util.concurrent)
ArrayList --> CopyOnWriteArrayList
HashSet、TreeSet --> CopyOnWriteArraySet、ConcurrentSkipListSet
HashMap、TreeMap -->ConcurrentHashMap、ConcurrentSkipListMap

一、页面优化的策略
。页面缓存+URL缓存+对象缓存:页面缓存跟URL缓存适合缓存时间较短的。对象缓存适合缓存时间较长的
。页面静态化,前后端分离:浏览器把静态页面缓存在客户端,只需要从服务端取动态数据。这样页面数据就
不需要重复下载。
。静态资源优化
。CDN优化

二、页面缓存:访问页面的时候不是让系统直接渲染,而是从缓存里取数据。如果没找到的话就手动渲染该模板,
然后把模板输出到客户端,同时将该结果缓存到redis中。这种缓存方式适用于比如像秒杀产品列表这样的一个页
,它的动态数据都是不会有太频繁的变动,所以将缓存数据设置为比如60s,既不会影响到数据的及时性,也会降
低频繁地对数据库的操作,从而提高性能。

2.1 步骤

。取缓存
。手动渲染模板
。结果输出

2.2 Code

2.2.1 之前未做缓存时的Code如下,此时每来一个请求都要与数据库进行IO操作,提取商品列表,然后在服务端
进行渲染,将结果返回给客户端

@RequestMapping("/to_list")
public String list(Model model,MiaoshaUser user) {
    model.addAttribute("user", user);

// 查询商品列表
List<GoodsVo> goodsList = goodsService.listGoodsVo();
model.addAttribute("goodsList", goodsList);
return "goods_list";
}

2.2.2 通过手动渲染页面:

@RequestMapping(value="/to_detail2/{goodsId}",produces="text/html")
@ResponseBody
public String detail2(HttpServletRequest request, HttpServletResponse response, Model model,MiaoshaUser user,
        @PathVariable("goodsId")long goodsId) {
    model.addAttribute("user", user);
    
    //取缓存
    String html = redisService.get(GoodsKey.getGoodsDetail, ""+goodsId, String.class);
    if(!StringUtils.isEmpty(html)) {
        return html;
    }
    //手动渲染
    GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
    model.addAttribute("goods", goods);
    
    long startAt = goods.getStartDate().getTime();
    long endAt = goods.getEndDate().getTime();
    long now = System.currentTimeMillis();
    
    int miaoshaStatus = 0;
    int remainSeconds = 0;
    if(now < startAt ) {//秒杀还没开始,倒计时
        miaoshaStatus = 0;
        remainSeconds = (int)((startAt - now )/1000);
    }else  if(now > endAt){//秒杀已经结束
        miaoshaStatus = 2;
        remainSeconds = -1;
    }else {//秒杀进行中
        miaoshaStatus = 1;
        remainSeconds = 0;
    }
    model.addAttribute("miaoshaStatus", miaoshaStatus);
    model.addAttribute("remainSeconds", remainSeconds);

    
    SpringWebContext ctx = new SpringWebContext(request,response,
            request.getServletContext(),request.getLocale(), model.asMap(), applicationContext );
    html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", ctx);
    if(!StringUtils.isEmpty(html)) {
        redisService.set(GoodsKey.getGoodsDetail, ""+goodsId, html);
    }
    return html;
}

三、URL缓存:指访问的是比上面的页面缓存粒度更小的缓存。比如我们要缓存某个商品的信息。此时的url格式就
如下:@RequestMapping(value="/detail/{goodsId}")
正常我们都是直接从数据库提取该商品的信息,Code如下:

@RequestMapping(value="/detail/{goodsId}")
@ResponseBody
public Result<GoodsDetailVo> detail(HttpServletRequest request, HttpServletResponse response, Model model,MiaoshaUser user,
        @PathVariable("goodsId")long goodsId) {
    GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
    long startAt = goods.getStartDate().getTime();
    long endAt = goods.getEndDate().getTime();
    long now = System.currentTimeMillis();
    int miaoshaStatus = 0;
    int remainSeconds = 0;
    if(now < startAt ) {//秒杀还没开始,倒计时
        miaoshaStatus = 0;
        remainSeconds = (int)((startAt - now )/1000);
    }else  if(now > endAt){//秒杀已经结束
        miaoshaStatus = 2;
        remainSeconds = -1;
    }else {//秒杀进行中
        miaoshaStatus = 1;
        remainSeconds = 0;
    }
    GoodsDetailVo vo = new GoodsDetailVo();
    vo.setGoods(goods);
    vo.setUser(user);
    vo.setRemainSeconds(remainSeconds);
    vo.setMiaoshaStatus(miaoshaStatus);
    return Result.success(vo);
}

但是假如我们通过构建缓存的方式:将当前商品的信息缓存在redis中。减少对数据库的IO操作。此时也会加快性能

@RequestMapping(value="/to_detail2/{goodsId}",produces="text/html")
@ResponseBody
public String detail2(HttpServletRequest request, HttpServletResponse response, Model model,MiaoshaUser user,
        @PathVariable("goodsId")long goodsId) {
    model.addAttribute("user", user);
    
    //取缓存
    String html = redisService.get(GoodsKey.getGoodsDetail, ""+goodsId, String.class);
    if(!StringUtils.isEmpty(html)) {
        return html;
    }
    //手动渲染
    GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
    model.addAttribute("goods", goods);
    
    long startAt = goods.getStartDate().getTime();
    long endAt = goods.getEndDate().getTime();
    long now = System.currentTimeMillis();
    
    int miaoshaStatus = 0;
    int remainSeconds = 0;
    if(now < startAt ) {//秒杀还没开始,倒计时
        miaoshaStatus = 0;
        remainSeconds = (int)((startAt - now )/1000);
    }else  if(now > endAt){//秒杀已经结束
        miaoshaStatus = 2;
        remainSeconds = -1;
    }else {//秒杀进行中
        miaoshaStatus = 1;
        remainSeconds = 0;
    }
    model.addAttribute("miaoshaStatus", miaoshaStatus);
    model.addAttribute("remainSeconds", remainSeconds);

    
    SpringWebContext ctx = new SpringWebContext(request,response,
            request.getServletContext(),request.getLocale(), model.asMap(), applicationContext );
    html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", ctx);
    if(!StringUtils.isEmpty(html)) {
        redisService.set(GoodsKey.getGoodsDetail, ""+goodsId, html);
    }
    return html;
}

四、对象缓存:粒度最小的,根据token来获得user对象。

public MiaoshaUser getByToken(HttpServletResponse response, String token) {
if(StringUtils.isEmpty(token)) {
return null;
}
MiaoshaUser user = redisService.get(MiaoshaUserKey.token, token, MiaoshaUser.class);
//延长有效期
if(user != null) {
addCookie(response, token, user);
}
return user;
}

五、页面缓存(前后端分离):常用技术AngularJs或者Vue.js。优点是利用浏览器的缓存。

5.1 将静态页面放在static目录下,同时将页面的名字命名为goods_detail.htm,而不是放在classpath:/templates/
5.2 在goods_list页面中,将:<td><a th:href="'/goods_detail.htm?goodsId='+${goods.id}">详情</a></td>
5.3 /detail/{goodsId} Controller的写法

@RequestMapping(value="/detail/{goodsId}")
@ResponseBody
public Result<GoodsDetailVo> detail(HttpServletRequest request, HttpServletResponse response, Model model,MiaoshaUser user,
                                    @PathVariable("goodsId")long goodsId) {
    GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
    long startAt = goods.getStartDate().getTime();
    long endAt = goods.getEndDate().getTime();
    long now = System.currentTimeMillis();
    int miaoshaStatus = 0;
    int remainSeconds = 0;
    if(now < startAt ) {//秒杀还没开始,倒计时
        miaoshaStatus = 0;
        remainSeconds = (int)((startAt - now )/1000);
    }else  if(now > endAt){//秒杀已经结束
        miaoshaStatus = 2;
        remainSeconds = -1;
    }else {//秒杀进行中
        miaoshaStatus = 1;
        remainSeconds = 0;
    }
    GoodsDetailVo vo = new GoodsDetailVo();
    vo.setGoods(goods);
    vo.setUser(user);
    vo.setRemainSeconds(remainSeconds);
    vo.setMiaoshaStatus(miaoshaStatus);
    return Result.success(vo);
}

5.4 异步请求,同时将数据填充在html页面中

function doMiaosha(){
$.ajax({
url:"/miaosha/do_miaosha",
type:"POST",
data:{
goodsId:$("#goodsId").val(),
},
success:function(data){
if(data.code == 0){
window.location.href="/order_detail.htm?orderId="+data.data.id;
}else{
layer.msg(data.msg);
}
},
error:function(){
layer.msg("客户端请求有误");
}
});

function render(detail){
var miaoshaStatus = detail.miaoshaStatus;
var remainSeconds = detail.remainSeconds;
var goods = detail.goods;
var user = detail.user;
if(user){
$("#userTip").hide();
}
$("#goodsName").text(goods.goodsName);
$("#goodsImg").attr("src", goods.goodsImg);
$("#startTime").text(new Date(goods.startDate).format("yyyy-MM-dd hh:mm:ss"));
$("#remainSeconds").val(remainSeconds);
$("#goodsId").val(goods.id);
$("#goodsPrice").text(goods.goodsPrice);
$("#miaoshaPrice").text(goods.miaoshaPrice);
$("#stockCount").text(goods.stockCount);
countDown();
}

5.5 页面静态化之后,验证将页面确实缓存在了客户端。打开开发者工具,查看:
Status Code :304,表示的意思是向服务端请求的页面的时候向服务端传递了一个If-Modified-Since参数,服务端
收到参数之后会检查当前页面有没有发生变化,假如没有发生变化的话就直接给客户端返回一个304的Code,表示可以
直接使用客户端缓存的静态页面。但是这个也有问题,要向客户端询问是否发生变化。为了避免向客户端发送
询问,可以在application.properties中设置如下的参数:

static

spring.resources.add-mappings=true
spring.resources.cache-period= 3600 //设置页面在静态页面中的缓存时间
spring.resources.chain.cache=true
spring.resources.chain.enabled=true
spring.resources.chain.gzipped=true
spring.resources.chain.html-application-cache=true
spring.resources.static-locations=classpath:/static/

加上如上的配置之后,响应头中有如下的响应参数:
Cache-Control:max-age=3600,表示浏览器缓存静态页面的时间。
在http1.1中还有一个Expire,跟上面的Cache-Control有异曲同工之妙,只不过如上的直接设置过期时间,另一个
是根据格林尼治时间来确定过期时间的,不太方便。

六、静态资源优化:
6.1 JS/CSS压缩,减少流量
6.2 多个JS/CSS,减少连接数
6.3 CDN就近访问

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,692评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,482评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,995评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,223评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,245评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,208评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,091评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,929评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,346评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,570评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,739评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,437评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,037评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,677评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,833评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,760评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,647评论 2 354

推荐阅读更多精彩内容