java实现秒杀业务之页面级高并发优化(页面缓存)

1、并发的瓶颈在于数据库(mysql),那如何减少对数据库的访问呢?

 

页面缓存:

package com.jack.seckill.redis;

public class GoodsKey extends BasePrefix{

	private GoodsKey(int expireSeconds,String prefix) {
		super(expireSeconds,prefix);
	}
	//页面缓存有效期都比较短,设置为60s,防止数据发生变化,页面还没有变
	public static GoodsKey getGoodsList=new GoodsKey(60,"gl");
}

 

import com.jack.seckill.redis.RedisService;
import com.jack.seckill.service.GoodsService;
import com.jack.seckill.service.SeckillUserService;
import com.jack.seckill.vo.GoodsVo;

/**
 * 跳转到商品页
 *
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

	@Autowired
	SeckillUserService userService;
	
	@Autowired
	RedisService redisService;
	
	
	@Autowired
	GoodsService goodsService;
	
	@Autowired
	ThymeleafViewResolver thymeleafViewResolver;
	
	@Autowired
	ApplicationContext applicationContext;
	
	
	
    @RequestMapping("/to_list")
    @ResponseBody
    public String list(HttpServletRequest request,HttpServletResponse response,Model model,SeckillUser seckillUser) {
    	model.addAttribute("user123", seckillUser);
//        return "goods_list";
        //使用页面缓存技术
        //第一步:从redis里面取缓存,看能否取到
        String html=redisService.get(GoodsKey.getGoodsList, "", String.class);
        if(!StringUtils.isEmpty(html)) {
        	return html;
        }
        
        //查询商品列表
    	List<GoodsVo> goodsList=goodsService.listGoodsVo();
    	model.addAttribute("goodsList", goodsList);
        //第二步:没有从缓存取出,就手动进行渲染[ctrl+shift+T 打开open type ctrl+T打开看继承关系]
        SpringWebContext ctx=new SpringWebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap(),applicationContext);
        html=thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
        if(!StringUtils.isEmpty(html)) {
        //第三步:保存到缓存里面去
        	redisService.set(GoodsKey.getGoodsList, "", html);
        }
        return html;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值