瀏覽代碼

同义词插件源码

liwh 1 月之前
父節點
當前提交
f57564d370

+ 8 - 0
.idea/.gitignore

@@ -0,0 +1,8 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Editor-based HTTP Client requests
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml

+ 1 - 1
config/jdbc-reload.properties

@@ -1,4 +1,4 @@
-jdbc.url=jdbc:mysql://10.168.1.47:18080/smart-search?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
+jdbc.url=jdbc:mysql://8.130.72.63:18080/smart-search?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
 jdbc.user=root
 jdbc.password=Taiji@2023#data
 jdbc.reload.synonym.sql=select sw_name from sys_synonym_word where UNIX_TIMESTAMP(update_time) >=@lastModifiedFrom and UNIX_TIMESTAMP(update_time)<=@lastModifiedTo

+ 0 - 3
config/socketPolicy.policy

@@ -1,3 +0,0 @@
-grant {
-   permission java.net.SocketPermission "10.168.1.47:18080","connect,resolve";
-};

+ 3 - 3
pom.xml

@@ -101,9 +101,9 @@
             <scope>test</scope>
         </dependency>
         <dependency>
-            <groupId>mysql</groupId>
-            <artifactId>mysql-connector-java</artifactId>
-            <version>8.0.21</version>
+            <groupId>com.mysql</groupId>
+            <artifactId>mysql-connector-j</artifactId>
+            <version>8.3.0</version>
         </dependency>
     </dependencies>
 

+ 1 - 1
src/main/assemblies/plugin.xml

@@ -35,7 +35,7 @@
             <useProjectArtifact>true</useProjectArtifact>
             <useTransitiveFiltering>true</useTransitiveFiltering>
             <includes>
-                <include>mysql:mysql-connector-java</include>
+                <include>com.mysql:mysql-connector-j</include>
             </includes>
         </dependencySet>
     </dependencySets>

+ 2 - 0
src/main/java/com/bellszhu/elasticsearch/plugin/DynamicSynonymPlugin.java

@@ -19,6 +19,8 @@ import com.bellszhu.elasticsearch.plugin.synonym.analysis.DynamicSynonymTokenFil
  */
 public class DynamicSynonymPlugin extends Plugin implements AnalysisPlugin {
 
+    public static String PLUGIN_NAME = "analysis-dynamic-synonym";
+
     @Override
     public Map<String, AnalysisProvider<TokenFilterFactory>> getTokenFilters() {
         Map<String, AnalysisProvider<TokenFilterFactory>> extra = new HashMap<>();

+ 91 - 48
src/main/java/com/bellszhu/elasticsearch/plugin/synonym/analysis/DBRemoteSynonymFile.java

@@ -5,11 +5,13 @@ import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 import org.apache.lucene.analysis.Analyzer;
 import org.apache.lucene.analysis.synonym.SynonymMap;
-import org.elasticsearch.core.PathUtils;
+import org.elasticsearch.SpecialPermission;
 import org.elasticsearch.env.Environment;
 
 import java.io.*;
 import java.nio.file.Path;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.sql.*;
 import java.util.ArrayList;
 import java.util.Properties;
@@ -58,21 +60,23 @@ public class DBRemoteSynonymFile implements SynonymFile {
         this.location = location;
         this.props = new Properties();
 
-        //读取当前 jar 包存放的路径
-        Path filePath = PathUtils.get(new File(DynamicSynonymPlugin.class.getProtectionDomain().getCodeSource()
-                        .getLocation().getPath())
-                        .getParent(), "config")
-                .toAbsolutePath();
-        this.conf_dir = filePath.resolve(DB_PROPERTIES);
+        this.conf_dir = this.env.configFile().resolve(DynamicSynonymPlugin.PLUGIN_NAME);
+        Path configFile = conf_dir.resolve(DB_PROPERTIES);
 
-        //判断文件是否存在
-        File configFile = conf_dir.toFile();
         InputStream input = null;
         try {
-            input = new FileInputStream(configFile);
+            logger.info("try load jdbc-reload.properties from {}", configFile);
+            input = new FileInputStream(configFile.toFile());
         } catch (FileNotFoundException e) {
-
-            logger.info("jdbc-reload.properties not find. " + e);
+            conf_dir = this.env.pluginsFile();
+            configFile = conf_dir.resolve(DB_PROPERTIES);
+            try {
+                logger.info("try load jdbc-reload.properties from {}", configFile);
+                input = new FileInputStream(configFile.toFile());
+            } catch (FileNotFoundException ex) {
+                // We should report origin exception
+                logger.error("jdbc-reload.properties not find. " + e);
+            }
         }
         if (input != null) {
 
@@ -80,12 +84,42 @@ public class DBRemoteSynonymFile implements SynonymFile {
                 props.load(input);
 
             } catch (Exception e) {
+                e.printStackTrace();
                 logger.error("fail to load the jdbc-reload.properties," + e);
             }
         }
+
         isNeedReloadSynonymMap();
     }
 
+    private void getDataBaseInfo(){
+
+        SpecialPermission.check();
+
+        AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
+
+            try {
+
+                Class.forName(props.getProperty("jdbc.driver"));
+
+                connection = DriverManager.getConnection(
+                        props.getProperty("jdbc.url"),
+                        props.getProperty("jdbc.user"),
+                        props.getProperty("jdbc.password")
+                );
+                statement = connection.createStatement();
+
+            } catch (Exception e) {
+
+                e.printStackTrace();
+
+                logger.error("数据库驱动、连接等属性信息加载失败", e);
+            }
+            return null;
+        });
+
+    }
+
     @Override
     public SynonymMap reloadSynonymMap() {
 
@@ -161,31 +195,18 @@ public class DBRemoteSynonymFile implements SynonymFile {
 
         try {
 
-            if (connection == null || statement == null) {
-                Class.forName(props.getProperty("jdbc.driver"));
-                connection = DriverManager.getConnection(
-                        props.getProperty("jdbc.url"),
-                        props.getProperty("jdbc.user"),
-                        props.getProperty("jdbc.password")
-                );
-                statement = connection.createStatement();
-            }
+            getDataBaseInfo();
+
             resultSet = statement.executeQuery(props.getProperty("jdbc.lastModified.synonym.sql"));
+
             while (resultSet.next()) {
                 last_modify_long = resultSet.getLong("version");
             }
-        } catch (ClassNotFoundException | SQLException e) {
+        } catch (Exception e) {
             logger.error("获取同义词库最后一次修改的时间",e);
         } finally {
 
-            try {
-                if (resultSet != null) {
-
-                    resultSet.close();
-                }
-            } catch (SQLException e) {
-                e.printStackTrace();
-            }
+            close(connection, statement, resultSet);
 
         }
         return last_modify_long;
@@ -200,26 +221,20 @@ public class DBRemoteSynonymFile implements SynonymFile {
         ArrayList<String> arrayList = new ArrayList<>();
 
         ResultSet resultSet = null;
+
         try {
-            if (connection == null || statement == null) {
-                Class.forName(props.getProperty("jdbc.driver"));
-                connection = DriverManager.getConnection(
-                        props.getProperty("jdbc.url"),
-                        props.getProperty("jdbc.user"),
-                        props.getProperty("jdbc.password")
-                );
-                statement = connection.createStatement();
-            }
+
+            getDataBaseInfo();
 
             String sql = props.getProperty("jdbc.reload.synonym.sql").replaceAll("@lastModifiedFrom",String.valueOf(lastModifiedFrom)).replaceAll("@lastModifiedTo",String.valueOf(lastModifiedTo));
 
 
             resultSet = statement.executeQuery(sql);
             while (resultSet.next()) {
-                String theWord = resultSet.getString("word");
+                String theWord = resultSet.getString("sw_name");
                 arrayList.add(theWord);
             }
-        }catch (ClassNotFoundException | SQLException e) {
+        }catch (Exception e) {
 
             e.printStackTrace();
 
@@ -227,18 +242,46 @@ public class DBRemoteSynonymFile implements SynonymFile {
 
         }finally {
 
-            try {
-                if (resultSet != null) {
-                    resultSet.close();
-                }
+            close(connection, statement, resultSet);
 
-            } catch (SQLException e) {
-                e.printStackTrace();
+        }
+
+        return arrayList;
+    }
+
+    /**
+     *
+     * @param connection
+     * @param statement
+     * @param resultSet
+     * select 查询关闭发方法:关闭结果集,SQL执行对象,连接对象三个的资源
+     */
+    public void close(Connection connection, Statement statement, ResultSet resultSet){
+
+        if (resultSet != null){
+            try{
+                resultSet.close();
+            }catch (Exception ex){
+                ex.printStackTrace();
+            }
+        }
+
+        if (statement != null){
+            try{
+                statement.close();
+            }catch (Exception ex){
+                ex.printStackTrace();
             }
+        }
 
+        if (connection != null){
+            try{
+                connection.close();
+            }catch (Exception ex){
+                ex.printStackTrace();
+            }
         }
 
-        return arrayList;
     }
 
 }