java实现秒杀业务之页面级高并发优化(URL缓存和对象缓存)
程序员文章站
2022-06-20 08:36:26
...
redis删除
/**
* 删除
* */
public boolean delete(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
long ret=jedis.del(realKey);
return ret>0;
}finally {
returnToPool(jedis);
}
}
对象缓存:
package com.jack.seckill.service;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jack.seckill.dao.SeckillDao;
import com.jack.seckill.domain.SeckillUser;
import com.jack.seckill.exception.GlobalException;
import com.jack.seckill.redis.RedisService;
import com.jack.seckill.redis.SeckillUserKey;
import com.jack.seckill.result.CodeMsg;
import com.jack.seckill.util.MD5Util;
import com.jack.seckill.util.UUIDUtil;
import com.jack.seckill.vo.LoginVo;
@Service
public class SeckillUserService {
public static final String COOKIE_NAME_TOKEN="token";
@Autowired
SeckillDao seckillDao;
@Autowired
RedisService redisService;
//取数据
public SeckillUser getById(long id) {
//实现对象缓存
//第一步:取缓存
SeckillUser seckillUser=redisService.get(SeckillUserKey.getById, ""+id, SeckillUser.class);
if(seckillUser!=null) {
return seckillUser;
}
//取数据库
seckillUser=seckillDao.getById(id);
if(seckillUser!=null) {
redisService.set(SeckillUserKey.getById, ""+id, seckillUser);
}
return seckillUser;
//return seckillDao.getById(id);
}
//修改数据
/**
* 注意:对象缓存如果有数据发生了更新,一定要将redis里面的缓存更新掉,否则出现数据的不一致
* 这也是对象缓存和页面缓存最大的区别
* 引用如别人的一定引用service层,而不是直接调别人的Dao,因为可能被人在service层调缓存
* @return
*/
public boolean updatePassword(String token,long id,String passwordNew) {
//取user
SeckillUser seckillUser=seckillDao.getById(id);
if(seckillUser==null) {
throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
}
//更新数据库
SeckillUser toBeUpdate=new SeckillUser();
toBeUpdate.setId(id);
toBeUpdate.setPassword(MD5Util.formPassToDBPass(passwordNew, seckillUser.getSalt()));
seckillDao.update(toBeUpdate);
//处理缓存
redisService.delete(SeckillUserKey.getById,""+id);
seckillUser.setPassword(toBeUpdate.getPassword());
redisService.set(SeckillUserKey.token,token,seckillUser);
return true;
}
}