java数据同步

来源:互联网 发布:为什么淘宝评论删不掉 编辑:程序博客网 时间:2024/05/17 09:35
1、自己写一个java上传数据程序打成jar包放在wrapper-windows里面去生成一个系统服务、默认未启动

以HttpClient形式上传数据


2、再写一个bat文件启动该服务

D:\BATCH\1.bat    testwrapper就是wrapper-windows生成出来的服务名称



@echo off
sc stop testwrapper
sc config testwrapper start= Auto

sc start testwrapper


rem -----------------------------------------------------------rem注释
rem @echo off
rem echo 确定要启动oracle 11g服务吗?
rem net start "OracleOraDb11g_home1TNSListener"
rem net start "OracleServiceORCL"
rem echo 启动Oracle 11g服务完成,请确认有没有错误发生。

rem @echo off
rem sc stop 服务名称
rem sc config 服务名称 start= Auto
rem sc start 服务名称

3、在电脑计划任务里添加一个定时任何去启动这个bat文件、bat文件又启动了第一步的服务、服务就开始跑java程序了

定时任务执行的bat文件就是:D:\BATCH\1.bat





public class MyConn {

static Connection getConn() {
   String driver = "com.mysql.jdbc.Driver";
   String url = "jdbc:mysql://xxxxxx:3326/xxxxxxxx";
   String username = "roo";
   String password = "root";
   Connection conn = null;
   try {
       Class.forName(driver); //classLoader,加载对应驱动
       conn = (Connection) DriverManager.getConnection(url, username, password);
   } catch (ClassNotFoundException e) {
       e.printStackTrace();
   } catch (SQLException e) {
       e.printStackTrace();
   }
   return conn;
}
}




public class HttpRequestUtils {
    
    /**
     * httpPost
     * @param url  路径
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPost(String url,JSONArray jsonParam){
        return httpPost(url, jsonParam, false);
    }
 
    /**
     * post请求
     * @param url         url地址
     * @param jsonParam     参数
     * @param noNeedResponse    不需要返回结�?
     * @return
     */
    public static JSONObject httpPost(String url,JSONArray jsonParam, boolean noNeedResponse){
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发�?�成功,并得到响�?**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数�?**/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /**把json字符串转换成json对象**/
                    jsonResult = JSONObject.fromObject(str);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
        e.printStackTrace();
        }
        return jsonResult;
    }
 
 
    /**
     * 发�?�get请求
     * @param url    路径
     * @return
     */
    public static JSONObject httpGet(String url){
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发�?�get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
 
            /**请求发�?�成功,并得到响�?**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数�?**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.fromObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                System.out.println("get请求提交失败:" + url);
            }
        } catch (IOException e) {
        e.printStackTrace();
        }
        return jsonResult;
    }
}





public class Main{

private static String url = "http://xxxxx:8080/xxxx/xxxx/xxxx/test.do";  
private static List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); 
    
public static void main(String[] args) throws IOException, SQLException {

Statement stmt = null;
ResultSet rs = null;
String sql = null;


try {
Connection conn = MyConn.getConn();
stmt = conn.createStatement();
sql = "select * from admin_user";
rs = stmt.executeQuery(sql);//执行sql语句
       ResultSetMetaData md = rs.getMetaData(); //获得结果集结构信息,元数据  
       int columnCount = md.getColumnCount();   //获得列数
while(rs.next()){
Map<String,Object> rowData = new HashMap<String,Object>();  
           for (int i = 1; i <= columnCount; i++) {  
               rowData.put(md.getColumnName(i), rs.getObject(i));  
           }  
           list.add(rowData);
}
} catch (Exception e) {
System.out.println("数据操作错误");
e.printStackTrace();
}
     
      JSONArray jsonarray = JSONArray.fromObject(list); 
    HttpRequestUtils.httpPost(url, jsonarray, false);

}
}





wrapper.conf  主要配置文件


#encoding=UTF-8
# Configuration files must begin with a line specifying the encoding
#  of the the file.


#********************************************************************
# Wrapper License Properties (Ignored by Community Edition)
#********************************************************************
# Professional and Standard Editions of the Wrapper require a valid
#  License Key to start.  Licenses can be purchased or a trial license
#  requested on the following pages:
# http://wrapper.tanukisoftware.com/purchase
# http://wrapper.tanukisoftware.com/trial


# Include file problems can be debugged by removing the first '#'
#  from the following line:
##include.debug


# The Wrapper will look for either of the following optional files for a
#  valid License Key.  License Key properties can optionally be included
#  directly in this configuration file.
#include ../conf/wrapper-license.conf
#include ../conf/wrapper-license-%WRAPPER_HOST_NAME%.conf


# The following property will output information about which License Key(s)
#  are being found, and can aid in resolving any licensing problems.
#wrapper.license.debug=TRUE


#********************************************************************
# Wrapper Localization
#********************************************************************
# Specify the locale which the Wrapper should use.  By default the system
#  locale is used.
#wrapper.lang=en_US # en_US or ja_JP


# Specify the location of the Wrapper's language resources.  If these are
#  missing, the Wrapper will default to the en_US locale.
wrapper.lang.folder=../lang


#********************************************************************
# Wrapper Java Properties
#********************************************************************
# Java Application
#  Locate the java binary on the system PATH:
wrapper.java.command=java
#  Specify a specific java binary:
#set.JAVA_HOME=/java/path
#wrapper.java.command=%JAVA_HOME%/bin/java


# Tell the Wrapper to log the full generated Java command line.
#wrapper.java.command.loglevel=INFO


# Java Main class.  This class must implement the WrapperListener interface
#  or guarantee that the WrapperManager class is initialized.  Helper
#  classes are provided to do this for you.  See the Integration section
#  of the documentation for details.
wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperSimpleApp


# Java Classpath (include wrapper.jar)  Add class path elements as
#  needed starting from 1
wrapper.java.classpath.1=../lib/wrappertest.jar
wrapper.java.classpath.2=../lib/wrapper.jar
wrapper.java.classpath.3=../application/uploaddata.jar
wrapper.java.classpath.4=../lib/mysql-connector-java-5.1.8-bin.jar
wrapper.java.classpath.5=../lib/json-lib-2.1-jdk15.jar
wrapper.java.classpath.6=../lib/commons-beanutils-1.7.0.jar
wrapper.java.classpath.7=../lib/commons-collections-3.1.jar
wrapper.java.classpath.8=../lib/commons-lang-2.5.jar
wrapper.java.classpath.9=../lib/commons-logging-1.1.1.jar
wrapper.java.classpath.11=../lib/ezmorph-1.0.3.jar
wrapper.java.classpath.12=../lib/httpclient-4.2.1.jar
wrapper.java.classpath.13=../lib/httpcore-4.2.1.jar
wrapper.java.classpath.14=../lib/httpmime-4.2.1.jar


# Java Library Path (location of Wrapper.DLL or libwrapper.so)
wrapper.java.library.path.1=../lib


# Java Bits.  On applicable platforms, tells the JVM to run in 32 or 64-bit mode.
wrapper.java.additional.auto_bits=TRUE


# Java Additional Parameters
wrapper.java.additional.1=


# Initial Java Heap Size (in MB)
wrapper.java.initmemory=128


# Maximum Java Heap Size (in MB)
wrapper.java.maxmemory=256


# Application parameters.  Add parameters as needed starting from 1
wrapper.app.parameter.1=com.kpt.main.Main


#********************************************************************
# Wrapper Logging Properties
#********************************************************************
# Enables Debug output from the Wrapper.
# wrapper.debug=TRUE


# Format of output for the console.  (See docs for formats)
wrapper.console.format=PM


# Log Level for console output.  (See docs for log levels)
wrapper.console.loglevel=INFO


# Log file to use for wrapper output logging.
wrapper.logfile=../logs/wrapper.log


# Format of output for the log file.  (See docs for formats)
wrapper.logfile.format=LPTM


# Log Level for log file output.  (See docs for log levels)
wrapper.logfile.loglevel=INFO


# Maximum size that the log file will be allowed to grow to before
#  the log is rolled. Size is specified in bytes.  The default value
#  of 0, disables log rolling.  May abbreviate with the 'k' (kb) or
#  'm' (mb) suffix.  For example: 10m = 10 megabytes.
wrapper.logfile.maxsize=0


# Maximum number of rolled log files which will be allowed before old
#  files are deleted.  The default value of 0 implies no limit.
wrapper.logfile.maxfiles=0


# Log Level for sys/event log output.  (See docs for log levels)
wrapper.syslog.loglevel=NONE


#********************************************************************
# Wrapper General Properties
#********************************************************************
# Allow for the use of non-contiguous numbered properties
wrapper.ignore_sequence_gaps=TRUE


# Do not start if the pid file already exists.
wrapper.pidfile.strict=TRUE


# Title to use when running as a console
wrapper.console.title=TmrUpLoadData


#********************************************************************
# Wrapper JVM Checks
#********************************************************************
# Detect DeadLocked Threads in the JVM. (Requires Standard Edition)
wrapper.check.deadlock=TRUE
wrapper.check.deadlock.interval=10
wrapper.check.deadlock.action=RESTART
wrapper.check.deadlock.output=FULL


# Out Of Memory detection.
# (Ignore output from dumping the configuration to the console.  This is only needed by the TestWrapper sample application.)
wrapper.filter.trigger.999=wrapper.filter.trigger.*java.lang.OutOfMemoryError
wrapper.filter.allow_wildcards.999=TRUE
wrapper.filter.action.999=NONE
#  Ignore -verbose:class output to avoid false positives.
wrapper.filter.trigger.1000=[Loaded java.lang.OutOfMemoryError
wrapper.filter.action.1000=NONE
# (Simple match)
wrapper.filter.trigger.1001=java.lang.OutOfMemoryError
# (Only match text in stack traces if -XX:+PrintClassHistogram is being used.)
#wrapper.filter.trigger.1001=Exception in thread "*" java.lang.OutOfMemoryError
#wrapper.filter.allow_wildcards.1001=TRUE
wrapper.filter.action.1001=RESTART
wrapper.filter.message.1001=The JVM has run out of memory.


#********************************************************************
# Wrapper Email Notifications. (Requires Professional Edition)
#********************************************************************
# Common Event Email settings.
#wrapper.event.default.email.debug=TRUE
#wrapper.event.default.email.smtp.host=<SMTP_Host>
#wrapper.event.default.email.smtp.port=25
#wrapper.event.default.email.subject=[%WRAPPER_HOSTNAME%:%WRAPPER_NAME%:%WRAPPER_EVENT_NAME%] Event Notification
#wrapper.event.default.email.sender=<Sender email>
#wrapper.event.default.email.recipient=<Recipient email>


# Configure the log attached to event emails.
#wrapper.event.default.email.attach_log=TRUE
#wrapper.event.default.email.maillog.lines=50
#wrapper.event.default.email.maillog.format=LPTM
#wrapper.event.default.email.maillog.loglevel=INFO


# Enable specific event emails.
#wrapper.event.wrapper_start.email=TRUE
#wrapper.event.jvm_prelaunch.email=TRUE
#wrapper.event.jvm_start.email=TRUE
#wrapper.event.jvm_started.email=TRUE
#wrapper.event.jvm_deadlock.email=TRUE
#wrapper.event.jvm_stop.email=TRUE
#wrapper.event.jvm_stopped.email=TRUE
#wrapper.event.jvm_restart.email=TRUE
#wrapper.event.jvm_failed_invocation.email=TRUE
#wrapper.event.jvm_max_failed_invocations.email=TRUE
#wrapper.event.jvm_kill.email=TRUE
#wrapper.event.jvm_killed.email=TRUE
#wrapper.event.jvm_unexpected_exit.email=TRUE
#wrapper.event.wrapper_stop.email=TRUE


# Specify custom mail content
wrapper.event.jvm_restart.email.body=The JVM was restarted.\n\nPlease check on its status.\n


#********************************************************************
# Wrapper Windows NT/2000/XP Service Properties
#********************************************************************
# WARNING - Do not modify any of these properties when an application
#  using this configuration file has been installed as a service.
#  Please uninstall the service before modifying this section.  The
#  service can then be reinstalled.


# Name of the service
wrapper.name=TmrUpLoadData


# Display name of the service
wrapper.displayname=TmrUpLoadData


# Description of the service
wrapper.description=Tmr UpLoad Data Application Description


# Service dependencies.  Add dependencies as needed starting from 1
wrapper.ntservice.dependency.1=


# Mode in which the service is installed.  AUTO_START, DELAY_START or DEMAND_START
wrapper.ntservice.starttype=AUTO_START


# Allow the service to interact with the desktop.
wrapper.ntservice.interactive=false