Das Konzept eines CircuitBreaker ist schon lange bekannt. Ich habe mir zu Studienzwecken einen selber gebaut - eigentlich zwei: Einer ist dafür da, das Logging von gleichartigen Exceptions zu drosseln, der andere für das Entzerren von Versuchen, Ressourcen von URLs nachzuladen. Diese spezielle Variante benötigte ich für EBMap4D: Falls einer der Tile-Server ausfällt, wird ansonsten ständig versucht, die Kacheln neu herunterzuladen. Das frisst nicht nur Rechenzeit, sondern ist auch unnütz.
Die beiden Implementierungen sind hier zur allgemeinen Begutachtung vorgestellt:
import org.slf4j.Logger;
public class ExceptionLoggingCircuitBreaker extends java.lang.Object
{
private final org.slf4j.Logger EXCEPTION_LOGGER;
private final long gracePeriod;
private java.util.Map<java.lang.String,java.lang.Long> lastLoggedTimestamps=new java.util.HashMap();
public ExceptionLoggingCircuitBreaker(Logger EXCEPTION_LOGGER,long gracePeriod)
{
super();
this.EXCEPTION_LOGGER = EXCEPTION_LOGGER;
this.gracePeriod=gracePeriod;
}
public void trace(java.lang.Throwable e)
{
java.lang.String msg = e.getMessage();
long now = java.time.Clock.systemDefaultZone().millis();
if (checkExpiration(msg,now))
{
EXCEPTION_LOGGER.trace(msg, e);
lastLoggedTimestamps.put(msg, now);
}
}
public void debug(java.lang.Throwable e)
{
java.lang.String msg = e.getMessage();
long now = java.time.Clock.systemDefaultZone().millis();
if (checkExpiration(msg,now))
{
EXCEPTION_LOGGER.debug(msg, e);
lastLoggedTimestamps.put(msg, now);
}
}
public void info(java.lang.Throwable e)
{
java.lang.String msg = e.getMessage();
long now = java.time.Clock.systemDefaultZone().millis();
if (checkExpiration(msg,now))
{
EXCEPTION_LOGGER.info(msg, e);
lastLoggedTimestamps.put(msg, now);
}
}
public void warn(java.lang.Throwable e)
{
java.lang.String msg = e.getMessage();
long now = java.time.Clock.systemDefaultZone().millis();
if (checkExpiration(msg,now))
{
EXCEPTION_LOGGER.warn(msg, e);
lastLoggedTimestamps.put(msg, now);
}
}
public void error(java.lang.Throwable e)
{
java.lang.String msg = e.getMessage();
long now = java.time.Clock.systemDefaultZone().millis();
if (checkExpiration(msg,now))
{
EXCEPTION_LOGGER.error(msg, e);
lastLoggedTimestamps.put(msg, now);
}
}
private boolean checkExpiration(java.lang.String msg,long now)
{
if (lastLoggedTimestamps.containsKey(msg) == false)
lastLoggedTimestamps.put(msg, Long.valueOf(0));
long backThen = lastLoggedTimestamps.get(msg);
return now - backThen > gracePeriod;
}
}
import de.elbosso.util.lang.TimestampedItem;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Map;
import java.util.Objects;
import org.slf4j.event.Level;
public class URLDownloadCircuitBreaker extends java.util.TimerTask
{
private final static org.slf4j.Logger CLASS_LOGGER =org.slf4j.LoggerFactory.getLogger(URLDownloadCircuitBreaker.class);
private final static org.slf4j.Logger EXCEPTION_LOGGER =org.slf4j.LoggerFactory.getLogger("ExceptionCatcher");
private java.util.Map<java.net.URL,TimestampedItem<java.util.concurrent.atomic.AtomicInteger> > map;
private final long retentionTimeInMillis;
private final int retentionCounterStartingValue;
private java.util.Timer timer;
public URLDownloadCircuitBreaker(long retentionTimeInMillis,int retentionCounterStartingValue)
{
super();
map=new java.util.HashMap();
this.retentionTimeInMillis=retentionTimeInMillis;
this.retentionCounterStartingValue=retentionCounterStartingValue;
timer=new java.util.Timer(true);
timer.schedule(this,retentionTimeInMillis,retentionTimeInMillis);
}
private void purge()
{
java.util.List<java.net.URL> toBeDeleted=new java.util.LinkedList();
for(Map.Entry<java.net.URL,TimestampedItem<java.util.concurrent.atomic.AtomicInteger> > entry:map.entrySet())
{
if(entry.getValue().hasBeenTouchedInTheLastMillis(retentionTimeInMillis)==false)
toBeDeleted.add(entry.getKey());
long now=java.util.Calendar.getInstance().getTimeInMillis();
long created=entry.getValue().getFirstseen().getTimeInMillis();
CLASS_LOGGER.trace(""+created+" "+(now-created));
}
for(java.net.URL t:toBeDeleted)
{
CLASS_LOGGER.trace("removing: "+t);
map.remove(t);
}
}
public int getCurrentlyBlockedUrlCount()
{
return map.size();
}
public java.awt.image.BufferedImage load(java.net.URL url) throws IOException
{
java.awt.image.BufferedImage rv=null;
if(url!=null)
{
if(map.containsKey(url))
{
map.get(url).touch();
int newValue=map.get(url).getItem().addAndGet(-1);
if(newValue==0)
map.remove(url);
}
if(map.containsKey(url)==false)
{
try
{
CLASS_LOGGER.trace("actually trying it: "+url);
rv = javax.imageio.ImageIO.read(url);
CLASS_LOGGER.trace("succeeded");
}
catch(java.io.IOException exp)
{
CLASS_LOGGER.trace("failed");
if(map.containsKey(url))
{
map.get(url).touch();
int newValue=map.get(url).getItem().addAndGet(-1);
if(newValue==0)
map.remove(url);
}
else
{
map.put(url, new TimestampedItem(new java.util.concurrent.atomic.AtomicInteger(retentionCounterStartingValue)));
}
throw exp;
}
}
}
return rv;
}
@Override
public void run()
{
purge();
CLASS_LOGGER.trace(Objects.toString(this)+" "+getCurrentlyBlockedUrlCount());
}
public static void main(java.lang.String[] args) throws MalformedURLException, InterruptedException
{
de.elbosso.util.Utilities.configureBasicStdoutLogging(Level.TRACE);
java.net.URL url=new java.net.URL("https://github.com/echo/echo");
java.net.URL url1=new java.net.URL("https://github.com/echo/echo1");
URLDownloadCircuitBreaker cb=new URLDownloadCircuitBreaker(300,10);
try
{
java.awt.image.BufferedImage bimg = cb.load(url);
if (bimg == null)
CLASS_LOGGER.trace("not tried");
else
CLASS_LOGGER.trace("should not get here");
} catch (java.io.IOException exp)
{
CLASS_LOGGER.trace("failed! ");
}
for(int i=0;i<8;++i)
{
CLASS_LOGGER.trace(i+" ");
java.net.URL u=((i<3)||(i>6))?url:url1;
try
{
java.awt.image.BufferedImage bimg = cb.load(u);
if (bimg == null)
CLASS_LOGGER.trace("not tried "+u);
else
CLASS_LOGGER.trace("should not get here");
} catch (java.io.IOException exp)
{
CLASS_LOGGER.trace("failed! "+u);
}
java.lang.Thread.currentThread().sleep(100);
}
try
{
java.awt.image.BufferedImage bimg = cb.load(url);
if (bimg == null)
CLASS_LOGGER.trace("not tried");
else
CLASS_LOGGER.trace("should not get here");
} catch (java.io.IOException exp)
{
CLASS_LOGGER.trace("failed!");
}
}
}
Precision Time Protocol
15.10.2021
Durch meinen Neffen wurde ich neulich auf ein Video im Internet aufmerksam gemacht, aus dem ich von der Existenz des Protokolls PTP oder Precision Time Protocol erfuhr. Hier einige Gedanken dazu
WeiterlesenAI und ML Android Basteln C und C++ Chaos Datenbanken Docker dWb+ ESP Wifi Garten Geo Go GUI Hardware Java Jupyter JupyterBinder Komponenten Links Linux Markdown Markup Music Numerik OpenSource PKI-X.509-CA Präsentationen Python QBrowser Rants Raspi Revisited Security Software-Test sQLshell TeleGrafana Verschiedenes Video Virtualisierung Windows Upcoming...
Als ich diese Lösung zur Darstellunbg und Analyse von beliebigen strukturierten Daten fand (das Beispiel erledigt das für ASN.1 kodierte Informationen), fasste ich den Entschluss, dass ich eine entsprechende Komponente in Java realisieren wollte.
WeiterlesenEine neue Version der sQLshell ist verfügbar!
WeiterlesenEin Influenzer würde einen solchen Artikel beginnen mit "Ich werde immer wieder gefragt, warum..." Da ich keiner bin kann ich so etwas nicht tun – statt dessen erläutere ich einfach das Szenario: Ich pflege diverse Open Source Projekte, die sich mit PKI und kryptographischen Timestamps. Jedoch benutzt die sQLshell elektronische Signaturen nur für die Verteilung der diversen Plugins.
WeiterlesenManche nennen es Blog, manche Web-Seite - ich schreibe hier hin und wieder über meine Erlebnisse, Rückschläge und Erleuchtungen bei meinen Hobbies.
Wer daran teilhaben und eventuell sogar davon profitieren möchte, muss damit leben, daß ich hin und wieder kleine Ausflüge in Bereiche mache, die nichts mit IT, Administration oder Softwareentwicklung zu tun haben.
Ich wünsche allen Lesern viel Spaß und hin und wieder einen kleinen AHA!-Effekt...
PS: Meine öffentlichen Codeberg-Repositories findet man hier.