Redis指令碼實現分布式鎖

來源:互聯網
上載者:User

Redis指令碼實現分布式鎖

redis被大量用在分布式的環境中,自然而然分布式環境下的鎖如何解決,立馬成為一個問題。例如我們當前的手遊項目,伺服器端是按業務模組劃分伺服器的,有應用服,戰鬥服等,但是這兩個vm都有可能同時改變玩家的屬性,這如果在同一個vm下面,就很容易加鎖,但如果在分布式環境下就沒那麼容易了,當然利用redis現有的功能也有解決辦法,比如redis的指令碼。

redis在2.6以後的版本中增加了Lua指令碼的功能,可以通過eval命令,直接在RedisServer環境中執行Lua指令碼,並且可以在Lua指令碼中調用Redis命令。
使用指令碼的好處:
1.減少網路開銷:可以把一些要批量處理的功能,發在一個指令碼裡面執行,減少用戶端和redis的互動次數
2.原子操作:這主要就是我們在這邊主要利用的功能,在分布式環境下保證資料的原子性。
3.複用:用戶端發送的指令碼會永久的儲存在redis中,這就意味著其他用戶端可以複用這一指令碼而不需要使用程式碼完成同樣的邏輯。

 下面先看一段lua指令碼:
local food=redis.call('hget',KEYS[1],'food');
food=food+ARGV[1];
redis.call('hset',KEYS[1],'food',food);
local diamond=redis.call('hget',KEYS[1],'diamond');
diamond=diamond+ARGV[2];
redis.call('hset',KEYS[1],'diamond',diamond);
注:redis.call是我們在指令碼中調用redis命令,KEYS和ARGV2個數組,分別是鍵和參數,下標都是從1開始的,不是0。
 這段指令碼的功能是取出 KEYS指定的玩家food(糧草)和diamond(玉石),然後就行修改,最後儲存在redis中,指令碼的執行,保證了整個操作的原子性。

下面我們用java代碼來看看具體的實現過程

Jedis jedis = new Jedis("192.168.128.128", 6379);
// 1.初始玩家資料到redis中
GamePlayer player = new GamePlayer();
player.setId(1001);
player.setName("ksfzhaohui");
player.setFood(100);
player.setDiamond(100);
 
Map<String, String> beanMap = BeanUtil.warp(player);// 將對象轉換成map
String beanKey = getRedisBeanKey(player.getClass(), player.getId());
System.out.println("key:" + beanKey);
jedis.hmset(beanKey, beanMap);// 將玩家資料儲存到redis中
 
首先類比了一個玩家將玩家資訊儲存在redis中,這邊的Id隨便寫了一個,正常的情況下都是通過redis的命令incr產生一個id
結果: 


 
String script = "local food=redis.call('hget',KEYS[1],'food');"
                + "food=food+ARGV[1];"
                + "redis.call('hset',KEYS[1],'food',food);"
                + "local diamond=redis.call('hget',KEYS[1],'diamond');"
                + "diamond=diamond+ARGV[2];"
                + "redis.call('hset',KEYS[1],'diamond',diamond);";
List<String> keys = new ArrayList<String>();
keys.add(beanKey);
List<String> args = new ArrayList<String>();
args.add("100");
args.add("100");
// 3.執行指令碼
jedis.eval(script, keys, args);

指定鍵和參考,執行指令碼,結果:

BeanUtil代碼:

public class BeanUtil {
    private static Logger logger = Logger.getLogger(BeanUtil.class);
    private static final String CLASS = "class";
 
    /**
    * 將指定的對象資料封裝成map
    *
    * @param bean
    *            對象資料
    * @return
    */
    @SuppressWarnings("all")
    public static Map<String, String> warp(Object bean) {
        Map<String, String> propertyMap = new HashMap<String, String>();
        try {
            PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass())
                    .getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : ps) {
                String propertyName = propertyDescriptor.getName();
                if (propertyName != null && !propertyName.equals(CLASS)) {
                    Method getter = propertyDescriptor.getReadMethod();
                    if (getter != null) {
                        propertyMap.put(propertyName,
                                String.valueOf(getter.invoke(bean, null)));
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
        return propertyMap;
    }
 
}
 
當然網上還有一些其他的方法,如: 用SETNX實現分布式鎖
可以參考:

Ubuntu 14.04下Redis安裝及簡單測試

Redis叢集明細文檔

Ubuntu 12.10下安裝Redis(圖文詳解)+ Jedis串連Redis

Redis系列-安裝部署維護篇

CentOS 6.3安裝Redis

Redis安裝部署學習筆記

Redis設定檔redis.conf 詳解

Redis 的詳細介紹:請點這裡
Redis 的:請點這裡

本文永久更新連結地址:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.