在服务器端自动刷新ApplicationScoped Bean

时间:2018-07-11 10:47:43

标签: java jsf-2 javabeans

我想在1小时后自动调用init()方法来刷新ApplicationScoped Bean。

在客户端,我可以创建一个按钮来更新Bean,但是我希望每隔一小时自动重新加载它,而无需单击或等待页面(因此没有Ajax回调)。

此外,我阅读了这篇文章: Refresh/Reload Application scope managed bean 但我想避免管理线程等。

是否可以在不更改bean范围的情况下实现?

谢谢

1 个答案:

答案 0 :(得分:-1)

我决心以这种方式实施:

1)添加Runnable实现

func applyOCR(image: UIImage, completionHandler: @escaping(_ error: Error ? , _ data : String ? ) - > Void) {



    let imageData: NSData = UIImageJPEGRepresentation(image, 0.2) !as NSData
    var base64 = imageData.base64EncodedString(options: .endLineWithCarriageReturn)


    var body = "{ 'requests': [ { 'image': { 'content': '\(base64)' }, 'features': [ { 'type': 'DOCUMENT_TEXT_DETECTION' } ],  'imageContext': {'languageHints': ['en']} } ] }";


    var session = URLSession.shared

    let url = URL(string: "https://vision.googleapis.com/v1/images:annotate?key={Your Key}")

    var request = NSMutableURLRequest(url: url!, cachePolicy:
        NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData,
        timeoutInterval: 30.0)

    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    request.httpBody = body.data(using: .utf8)


    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        data,
        response,
        error in

        if let error = error {
            print(error.localizedDescription)
            completionHandler(error, nil)
        }


        if let data = data {

            do {
                let string1 = String(data: data, encoding: String.Encoding.utf8) ? ? "Data could not be printed"
                //print(string1)

                var json =
                    try JSONSerialization.jsonObject(with: data, options: .allowFragments) as![String: Any]
                if let responseData = json["responses"] as ? NSArray {

                    if let levelB = responseData[0] as ? [String: Any] {

                        if let levelC = levelB["fullTextAnnotation"] as ? [String: Any] {


                            if let text = levelC["text"] as ? String {

                                completionHandler(nil, text)
                                return

                            }

                        }

                    }



                }

                let error = NSError(domain: "", code: 401, userInfo: [NSLocalizedDescriptionKey: "Invaild access token"])
                completionHandler(error, nil)
                return


            } catch {
                print("error parsing \(error)")
                completionHandler(error, nil)
                return



            }

        }

    })

    task.resume()

}

2)添加实现方法“运行”

@ManagedBean(eager= true, name="dashboardbean")
@ApplicationScoped
public class DashboardBean implements Serializable, Runnable {

3)实现了bean的init方法

@Override
public void run() {
    System.out.println("##########populateData#############");
    allServerCount = numbersServer.get("serverCount");
    System.out.println("###########server "+allServerCount+"#############");
    System.out.println("###########end populateData#############");
}

4)添加了销毁调度程序的部分

@PostConstruct
public void init() {
    System.out.println("##########init#############");
    scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(this, 0, 2, TimeUnit.MINUTES);
    System.out.println("##########end#############");
}

这是每2分钟在日志上生成的输出

private ScheduledExecutorService scheduler; 

@PreDestroy
public void destroy() {
    scheduler.shutdownNow();
}