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

北京做网站比较有名的公司有哪些今日头条搜索优化

北京做网站比较有名的公司有哪些,今日头条搜索优化,北海网站建设,公网怎么做网站1、手写 Redis 分布式锁,包括上锁、解锁、自动续期。 此功能实现采用 Lua脚本实现,Lua脚本可以保证原子性。 setnx可以实现分布式锁,但是无法实现可重入锁,所以用hset来代替setnx实现可重入的分布式锁。 -- lock if redis.call…

1、手写 Redis 分布式锁,包括上锁、解锁、自动续期。

此功能实现采用 Lua脚本实现,Lua脚本可以保证原子性。

setnx可以实现分布式锁,但是无法实现可重入锁,所以用hset来代替setnx实现可重入的分布式锁。

-- lock
if redis.call('exists',KEYS[1]) == 0 or redis.call('hexists',KEYS[1],ARGV[1]) == 1 thenredis.call('hincrby',KEYS[1],ARGV[1],1)redis.call('expire',KEYS[1],ARGV[2])return 1
elsereturn 0
end
-- unlock
if redis.call('hexists',KEYS[1],ARGV[1]) == 0 thenreturn nil
elseif redis.call('hincrby',KEYS[1],ARGV[1],-1) == 0 thenreturn redis.call('del',KEYS[1])
elsereturn 0
end
-- expire
if redis.call('hexists',KEYS[1],ARGV[1]) == 0 thenreturn redis.call('expire',KEYS[1],ARGV[2])
elsereturn 0
end

2、工具类如下:

/*** @author xxx* @descpription: 自定义redis分布式锁* @date 2024/7/24*/
public class MyRedissonLua implements Lock {/***  加锁脚本*/private static final String lockScript ="if redis.call('exists',KEYS[1]) == 0 or redis.call('hexists',KEYS[1],ARGV[1]) == 1 then " +"redis.call('hincrby',KEYS[1],ARGV[1],1)    " +"redis.call('expire',KEYS[1],ARGV[2])    " +"return 1 " +"else    " +"return 0 " +"end";/*** 解锁脚本*/private static final String unLockScript ="if redis.call('HEXISTS',KEYS[1],ARGV[1]) == 0 then    " +"return nil " +"elseif redis.call('HINCRBY',KEYS[1],ARGV[1],-1) == 0 then    " +"return redis.call('del',KEYS[1]) " +"else    " +"return 0 " +"end";/***  续期脚本*/private static final String expireScript ="if redis.call('HEXISTS',KEYS[1],ARGV[1]) == 0 then  " +"    return redis.call('EXPIRE',KEYS[1],ARGV[2])     " +"else " +"    return 0 " +"end";private StringRedisTemplate stringRedisTemplate;/*** KEYS[1]*/private String lockName;/*** ARGV[1]*/private String uuidValue;/*** ARGV[2]*/private Long expireTime;public MyRedissonLua(StringRedisTemplate stringRedisTemplate, String lockName,String uuid) {this.stringRedisTemplate = stringRedisTemplate;this.lockName = lockName;this.uuidValue = uuid + ":" + Thread.currentThread().getId();this.expireTime = 30L;}@Overridepublic void lock() {tryLock();}@Overridepublic void unlock() {Long flag = stringRedisTemplate.execute(new DefaultRedisScript<>(unLockScript, Long.class), Arrays.asList(lockName), uuidValue);System.out.println("unlock lockName:" + lockName + "\tuuidValue:" + uuidValue + "\t expireTime:" + expireTime);if(flag == null) {throw new IllegalMonitorStateException("释放锁异常");}else {System.out.println("释放锁成功");}}@Overridepublic boolean tryLock() {boolean result;try {result = tryLock(-1L, TimeUnit.SECONDS);} catch (InterruptedException e) {throw new RuntimeException(e);}return result;}@Overridepublic boolean tryLock(long time, TimeUnit unit) throws InterruptedException {if (time == -1L){System.out.println("lockName:" + lockName + "\tuuidValue:" + uuidValue + "\t expireTime:" + expireTime);//可重入while (!stringRedisTemplate.execute(new DefaultRedisScript<>(lockScript, Boolean.class), Arrays.asList(lockName), uuidValue, String.valueOf(expireTime))){TimeUnit.MILLISECONDS.sleep(60);}//后台扫描程序,检测key的ttl,来实现续期reExpire();return true;}return false;}private void reExpire() {//每 10s 续期一次new Timer().schedule(new TimerTask(){@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + " 续期");if (stringRedisTemplate.execute(new DefaultRedisScript<>(lockScript, Boolean.class), Arrays.asList(lockName), uuidValue, String.valueOf(expireTime))){reExpire();}}},(this.expireTime * 1000) / 3);}@Overridepublic void lockInterruptibly() {}@Overridepublic Condition newCondition() {return null;}
}

3、由于实现分布式锁的方式有很多,故采用工厂模式

/*** @author xxx* @descpription: 工厂模式生产分布式锁* @date 2024/7/24*/
@Component
public class DistributedLockFactory {private String lockName;private String uuid;@Resourceprivate StringRedisTemplate stringRedisTemplate;public DistributedLockFactory() {this.uuid = IdUtil.simpleUUID();}public Lock getDistributedLock(String lockType){if (lockType == null) {return null;}if (lockType.equals("REDIS")){lockName = "zzyyRedisLock";return new MyRedissonLua(stringRedisTemplate, lockName,uuid);} else if (lockType.equals("ZOOKEEPER")) {lockName = "zzyyZookeeperLock";//...Zookeeper版本的分布式锁return null;}return null;}
}

4、业务代码

import cn.hutool.core.util.IdUtil;
import com.coco.service.ICardService;
import com.coco.utils.lua.DistributedLockFactory;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;/*** @author xxx* @descpription: * @date 2024/7/18*/
@Service
public class ICardServiceImpl implements ICardService {@Resourceprivate StringRedisTemplate stringRedisTemplate;private static final String KEY = "sale001";@Value("${server.port}")private String port;@Resourceprivate RedissonClient redissonClient;/*** 自定义的redis分布式锁*/
//    private Lock lock = new MyRedissonLua(stringRedisTemplate, "zzyyRedisLock");/*** 通过工厂获取自定义的redis分布式锁*/@Resourceprivate DistributedLockFactory distributedLockFactory;@Overridepublic String sale() {version7();return "success";}private void version7() {Lock lock = distributedLockFactory.getDistributedLock("REDIS");lock.lock();try{String countStr = stringRedisTemplate.opsForValue().get(KEY);Integer count = countStr == null ? 0 : Integer.parseInt(countStr);if (count > 0) {stringRedisTemplate.opsForValue().set(KEY,String.valueOf(--count));System.out.println("剩余库存为:" + stringRedisTemplate.opsForValue().get(KEY) + "服务端口:" + port);//演示自动续期try {TimeUnit.SECONDS.sleep(120);} catch (InterruptedException e) {throw new RuntimeException(e);}}else {System.out.println("没有库存了");}}finally {lock.unlock();}}/*** 可重入锁*/private void version6() {Lock lock = distributedLockFactory.getDistributedLock("REDIS");lock.lock();try{String countStr = stringRedisTemplate.opsForValue().get(KEY);Integer count = countStr == null ? 0 : Integer.parseInt(countStr);if (count > 0) {stringRedisTemplate.opsForValue().set(KEY,String.valueOf(--count));System.out.println("剩余库存为:" + stringRedisTemplate.opsForValue().get(KEY) + "服务端口:" + port);//可重入testReEntry();}else {System.out.println("没有库存了");}}finally {lock.unlock();}}/***  可重入锁*/private void testReEntry() {Lock lock = distributedLockFactory.getDistributedLock("REDIS");lock.lock();try {System.out.println("===========再次获取锁=============");} finally {lock.unlock();}}/*** 通过Lua脚本实现分布式锁解锁*/private void version5() {String key = "zzyyRedisLock";String uuidValue = IdUtil.simpleUUID() +":" + Thread.currentThread().getId();//分布式锁(自旋)while (!stringRedisTemplate.opsForValue().setIfAbsent(key, uuidValue,10,TimeUnit.SECONDS)) {try {TimeUnit.MILLISECONDS.sleep(20);} catch (InterruptedException e) {throw new RuntimeException(e);}}try {String countStr = stringRedisTemplate.opsForValue().get(KEY);Integer count = countStr == null ? 0 : Integer.parseInt(countStr);if (count > 0) {stringRedisTemplate.opsForValue().set(KEY,String.valueOf(--count));System.out.println("剩余库存为:" + stringRedisTemplate.opsForValue().get(KEY) + "服务端口:" + port);}else {System.out.println("没有库存了");}} finally {String script ="if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +"    return redis.call(\"del\",KEYS[1])\n" +"else\n" +"    return 0\n" +"end";stringRedisTemplate.execute(new DefaultRedisScript<>(script, Boolean.class),Arrays.asList(key), uuidValue);}}/*** 添加判断防止解锁解的不是同一把锁*/private void version4() {String key = "zzyyRedisLock";String uuidValue = IdUtil.simpleUUID()+":" + Thread.currentThread().getId();//分布式锁(自旋)while (!stringRedisTemplate.opsForValue().setIfAbsent(key, uuidValue,10,TimeUnit.SECONDS)) {try {TimeUnit.MILLISECONDS.sleep(20);} catch (InterruptedException e) {throw new RuntimeException(e);}}try {String countStr = stringRedisTemplate.opsForValue().get(KEY);Integer count = countStr == null ? 0 : Integer.parseInt(countStr);if (count > 0) {stringRedisTemplate.opsForValue().set(KEY,String.valueOf(--count));System.out.println("剩余库存为:" + stringRedisTemplate.opsForValue().get(KEY) + "服务端口:" + port);}else {System.out.println("没有库存了");}} finally {if (Objects.equals(uuidValue, stringRedisTemplate.opsForValue().get(key))){stringRedisTemplate.delete(key);}}}/*** 通过setnx实现redis分布式锁*/private void version3() {String key = "zzyyRedisLock";String uuidValue = IdUtil.simpleUUID()+":" + Thread.currentThread().getId();//分布式锁Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, uuidValue);if (flag) {try {String countStr = stringRedisTemplate.opsForValue().get(KEY);Integer count = countStr == null ? 0 : Integer.parseInt(countStr);if (count > 0) {stringRedisTemplate.opsForValue().set(KEY,String.valueOf(--count));System.out.println("剩余库存为:" + stringRedisTemplate.opsForValue().get(KEY) + "服务端口:" + port);}else {System.out.println("没有库存了");}} finally {if (Objects.equals(uuidValue, stringRedisTemplate.opsForValue().get(key))){stringRedisTemplate.delete(key);}}}else {try {TimeUnit.MILLISECONDS.sleep(20);} catch (InterruptedException e) {throw new RuntimeException(e);}sale();}}/*** juc的lock锁*/private void version2() {
//        lock.lock();
//        try {
//            Integer count = (Integer) redisTemplate.opsForValue().get(KEY);
//            if (count > 0) {
//                redisTemplate.opsForValue().decrement(KEY);
//                System.out.println("剩余库存为:" + redisTemplate.opsForValue().get(KEY) + "服务端口:" + port);
//            }else {
//                System.out.println("没有库存了");
//            }
//        } finally {
//            lock.unlock();
//        }}
}

http://www.hrbkazy.com/news/12970.html

相关文章:

  • 广州网站建设公司排行惠州seo博客
  • 少女前线b站服百度搜索风云榜电视剧
  • 网站内的链接怎么做网络服务器图片
  • 移动端web app网站开发重庆seo论坛
  • 摄影网页设计方案上海单个关键词优化
  • 怎么把网站做成软件厦门seo优化
  • 内蒙古知名网站建设seo代理计费系统
  • 做网站推广电话什么是整合营销概念
  • phpcms 友情链接 网站名称字数抖音怎么推广引流
  • 权威的企业网站建设营销型网站推广方案
  • 自己建网站能赚钱吗软文范例大全800
  • 婚庆公司网站模板seo技巧分享
  • wordpress找不到对象西安seo托管
  • 邯郸做网站哪儿好制定营销推广方案
  • 做网站用什么语言简单亚马逊关键词排名提升
  • 网站开发有哪些百度网盘下载的文件在哪
  • 如何查网站的百度快照怎么创建网站赚钱
  • 深圳智加设计公司如何优化网站快速排名
  • 网站开发总监招聘免费的发帖收录网站
  • 做设计下素材有比较好的网站网络营销工程师前景
  • wordpress cdn jqueryseo研究中心教程
  • 删除网站域名下载app
  • 服装网站建设策划书论文seo实战技术培训
  • 做网站推广需要花多少钱制作一个简单的html网页
  • 做网站什么公司链接买卖平台
  • 哪些网站的做的好看的图片seo中国官网
  • qq空间 同步 wordpressseo关键词排名优化怎么收费
  • 做网站数据库要建什么表北京做网站公司哪家好
  • 韩国网站免费模板阜新网络推广
  • 唐山 建设工程信息网站网站seo外链建设