[英]How to make a client fetch everytime data is updated?
我有一個項目,它由以下部分組成:
現在我問自己的是,如何確保客戶端在通過 Web 儀表板更新后立即獲取新數據? 每隔幾秒鍾獲取一次似乎不是正確的方法,套接字連接會是一個好的解決方案嗎?
如果您有任何想法,請告訴我,謝謝。
作為一種選擇,您可以在創建/更新/刪除表行時向隊列發送消息。 這樣,您將異步進行更改,並且可以根據它們做出反應。
在發布者方面,您可以擁有以下內容:
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.PostPersist;
import javax.persistence.PostRemove;
import javax.persistence.PostUpdate;
import static javax.persistence.GenerationType.IDENTITY;
@Entity
@EntityListeners(ExamplePersonEntityListener.class)
class ExamplePerson {
@Id
@GeneratedValue(strategy=IDENTITY)
private Long id;
private String name;
private String lastname;
}
@Configurable
class ExamplePersonEntityListener extends AbstractEntityyListener<ExamplePersonEntityApplicationEvent> {
@PostPersist
public void examplePersonCreated(ExamplePerson model) {
this.broadcast(new ExamplePersonEntityApplicationEvent(EventActionn.CREATE, model));
}
@PostUpdate
public void examplePersonUpdated(ExamplePerson model) {
this.broadcast(new ExamplePersonEntityApplicationEvent(EventActionn.UPDATE, model));
}
@PostRemove
public void examplePersonRemoved(ExamplePerson model) {
this.broadcast(new ExamplePersonEntityApplicationEvent(EventActionn.DELETE, model));
}
}
public class ExamplePersonEntityApplicationEvent extends EntityApplicationEventt<ExamplePerson> {
protected ExamplePersonEntityApplicationEvent(EventActionn action, ExamplePerson model) {
super(action, model);
}
}
@Configurable
abstract class AbstractEntityyListener<T extends EntityApplicationEventt<?>> {
@Autowired
private ObjectFactory<ApplicationEventPublisher> appEvents;
public final void setApplicationEventPublisher(ObjectFactory<ApplicationEventPublisher> appEvents) {
this.appEvents = appEvents;
}
protected final void broadcast(T event) {
assert this.appEvents != null;
this.appEvents.getObject().publishEvent(event);
}
}
class EntityApplicationEventt<T extends Object> extends ApplicationEvent {
private final EventActionn action;
private final T model;
protected EntityApplicationEventt(EventActionn action, T model) {
super(model);
this.action = action;
this.model = model;
}
public EventActionn getAction() {
return this.action;
}
public Long getId() {
return (Long)this.getSource();
}
public T getModel() {
return this.model;
}
}
enum EventActionn {
CREATE,
UPDATE,
DELETE,
}
您將需要在客戶端上創建一個隊列和該隊列的訂閱者。
一般來說,有兩種方式:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.