1. 程式人生 > >定時任務:每隔一段時間從資料庫獲取最新記錄

定時任務:每隔一段時間從資料庫獲取最新記錄

package com.byhealth.act.firstactivity.scheduler;

/**
 * Created by XXX on 2017/10/17.
 */
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.ArrayList;
import com.byhealth.act.firstactivity.redis.JedisService;
import com.byhealth.act.firstactivity.vo.JldProductVO;
import org.springframework.beans.factory.annotation.Value;

@Component
public class Schedule{

    //資料庫登入使用者
    @Value("${DB_USER}")
    private String DB_USER;

    //資料庫登入密碼
    @Value("${DB_PASSWORD}")
    private String DB_PASSWORD;

    //資料庫連線地址
    @Value("${DB_URL}")
    private String DB_URL;

    @Autowired
    protected JedisService jedisService;

    //每隔30分鐘執行一次
   // @Scheduled(cron = "0 */30 * * * ?")
    public void findAllProd(){
        try{
            // 建立一個數據庫連線
            Connection con = null;
            PreparedStatement pre = null;
            ResultSet result = null;
            try{
                // 載入Oracle驅動程式
                Class.forName("oracle.jdbc.driver.OracleDriver");
                String url = DB_URL;
                String user = DB_USER;
                String password = DB_PASSWORD;
                //獲取連線
                con = DriverManager.getConnection(url, user, password);

                String sql = "select * from product where BRAND='XX'   ";
                pre = con.prepareStatement(sql);
                result = pre.executeQuery();

                List<JldProductVO> list = new ArrayList<JldProductVO>();
                 while (result.next()){
                     if(result.getString("brand_name")!=null){
                         JldProductVO vo = new JldProductVO();
                         vo.setCodeNum(result.getString("brand_name").toString());
                         list.add(vo);
                     }
                }
                jedisService.delString("jldList");
                //設定時長30分鐘
                jedisService.setObject("jldList", list,1800);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try{
                    if (result != null)
                        result.close();
                    if (pre != null)
                        pre.close();
                    if (con != null)
                        con.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}