分析和解決:ERR Error compiling script (new function): user_script:1: 'end' expected near '

事件:原本lua腳本讀的還好好的,下午改了讀取方式後就報錯:

Error in execution; nested exception is io.lettuce.core.RedisCommandExecutionException:
ERR Error compiling script (new function): user_script:1: 'end' expected near '<eof>'

解決過程:反覆試了好幾次,用測試類測試本地redis的服務是否正常後,發現redis服務是好的

根據報的錯,可以看出是lua腳本出的問題,於是把讀取到的lua腳本打印出來後發現:


[2020-04-08 21:27:35,788]-[INFO]-[main]-[com.util.ReadConfigsPathUtil:57]-luaScript:local function get_next_seq() local key = tostring(KEYS[1]) local incr_amoutt = tonumber(KEYS[2]) local seq = tonumber(KEYS[3]) local month_in_seconds = 24 * 60 * 60 * 30 if (1 == redis.call(‘setnx’, key, seq)) then redis.call(‘expire’, key, month_in_seconds) return seq else local nextSeq = redis.call(‘incrby’, key, incr_amoutt) return nextSeq endendreturn get_next_seq()


解決方法:可以發現最後一行出現了”endendreturn “相連,所以自然是錯誤的,於是修改後:在每讀一行之後都回車換行,完美解決問題!!!

類似問題:出現問題之後我去查了同僚們也有類似的問題,他們是出在配置文件配置redis時,超時時間寫的是0,可以改成1000或更多毫秒
spring.redis.pool.timeout= 2000ms
另外還有是由於腳本中有中文的問題,刪掉後就好了!!!
還有:在項目中配置文件中,連接redis,配置了密碼,密碼錯誤,或者配置文件中沒有寫密碼,就會報錯,可以考慮取消密碼或者修改配置文件,添加密碼。
在springboot項目中原本用的ClassPathResource 讀取的配置文件,但是考慮到在生產環境時配置文件或者腳本文件需要單獨拿出來,但是放在resouce目錄下打包的時候就會打進去,無法解耦,所以在根目錄下建了config目錄,把腳本放在跟目錄下:

在這裏插入圖片描述

讀取lua腳本的方法:

package com.test.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.DefaultScriptExecutor;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.List;

@Component
public class RedisUtil {
    private static final Logger log =  LoggerFactory.getLogger(RedisUtil.class);

    private static StringRedisTemplate redisStringTemplate;

    private static RedisScript<Long> redisScript;

    private static DefaultScriptExecutor<String> scriptExecutor;

    private RedisUtil(StringRedisTemplate template) throws IOException {
        RedisUtil.redisStringTemplate = template;
        
        // 初始化lua腳本調用 的redisScript 和 scriptExecutor
        
         //第一種辦法:通過ClassPathResource讀取resource下的lua腳本
//        ClassPathResource luaResource = new ClassPathResource("luaScript/genSeq.lua");
//        EncodedResource encRes = new EncodedResource(luaResource, "UTF-8");
//        String luaString = FileCopyUtils.copyToString(encRes.getReader());

         //第二種辦法,讀取跟目錄下的config目錄後再按行讀取
          String luaString= ReadConfigsPathUtil.readFileContent("luaScript/genSeq.lua");
//        log.info("luaString:"+luaString);

          redisScript = new DefaultRedisScript<>(luaString, Long.class);
          scriptExecutor = new DefaultScriptExecutor<>(redisStringTemplate);
    }
    public static Long getBusiSeq(List<String> Busilist) {
        Long seqFromRedis = scriptExecutor.execute(redisScript, Busilist);
        return  seqFromRedis;
    }
}

方法:ReadConfigsPathUtil.readFileContent(“luaScript/genSeq.lua”)

package com.test.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class ReadConfigsPathUtil {
    private static final Logger log =  LoggerFactory.getLogger(ReadConfigsPathUtil.class);
    private ReadConfigsPathUtil() {}
    private static Properties properties = null;

    public static String  getPropertiesPath(String luaScriptPath) {
        String sysPath=getrelativePath();
        String osType=System.getProperties().getProperty("os.name").toLowerCase();
        log.info("sysPath:"+sysPath);
        String filepath="";
        if(osType.startsWith("windows")) {
            filepath=new StringBuffer(sysPath).append(File.separator)
                    .append("config").append(File.separator).append(luaScriptPath).toString();
            log.info("filepath:"+filepath);
        }else if(osType.startsWith("linux")) {//啓動腳本在哪個路徑,sysPath的值就是當前路徑的pwd的值
            int len=sysPath.length();
            int lenBin=("/bin").length();//我的啓動腳本在bin目錄下
            sysPath=sysPath.substring(0,(len-lenBin));
            filepath=new StringBuffer(sysPath).append(File.separator)
                    .append("config").append(File.separator).append(luaScriptPath).toString();
            log.info("filepath:"+filepath);
        }
        return filepath;
    }
  
    public static String getrelativePath() {
        return System.getProperty("user.dir");
    }

    public static String readFileContent(String luaScriptPath) {
        String filename=getPropertiesPath(luaScriptPath);
        File file = new File(filename);
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
                sbf.append("\r\n");//此處必須換行,這是出現RedisCommandExecutionException異常的原因
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return sbf.toString();
    }
}

與君共勉!!!也歡迎留言交流哦~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章