Jedis keyspace notification event for "set" not working - java

So im trying to implement basic listener for when some value is set on redis, but when i set some value nothing happens and only expiry event gets called.
Subscriber
public class Subscriber {
private static JedisPool pool;
public static void main(String[] args) {
JedisPool pool = new JedisPool("localhost");
Jedis jedis = pool.getResource();
jedis.psubscribe(new SubListener(), "*");
}
}
SubListener
public class SubListener extends JedisPubSub {
#Override
public void onPSubscribe(String pattern, int subscribedChannels) {
System.out.println("onPSubscribe "
+ pattern + " " + subscribedChannels);
}
#Override
public void onPMessage(String pattern, String channel, String message) {
System.out
.println("onPMessage pattern "
+ pattern + " " + channel + " " + message);
}
}
Edit: i found out that i had the notify-keyspace-events in config set to Ex. Now i set it to KEA to call on every event but what should i use to only call the event on set

To only call the event on set, set the config to Ks

Related

how to find all routes on a camel context

I'm trying to find all routes associated with a camel context?
I can't find the camel exchange getContext() data sheets so I know what methods can be called?
I have a dynamic route builder, drop a config file and the route gets created.
I need to create the routes in registry, as not started, and use a JGroups/Controlbus route that controls who is the active route. But I can't figure out how to get all routes associated with a camel context? if you can shed some light on this, I'd really be in your dept. thanks in advance.
This is what I have but I can't get to work, found on stacktrace.
#Override
public void process(Exchange exchange) throws Exception {
List<ProcessorDefinition<?>> outputProcessorDefs = exchange.getContext().getRouteDefinition("[routeId]").getOutputs();
for ( ProcessorDefinition rte : outputProcessorDefs ) {
log.info("ROUTES: " + rte);
}
}
thanks to a question answered by Claus How to find all Endpoints of route (Apache Camel, Java)
I was able to locate some info and found another simpler way to do this.
public void process(Exchange exchange) throws Exception {
List<Route> routeList = exchange.getContext().getRoutes();
for ( Route rte : routeList ) {
log.info("ROUTES: " + rte.getId());
}
This is my test for JGroups ControlBus management made possible by getRoutes() for dynamic route creation.
public class EndpointControlBusFileRouteBuilder extends RouteBuilder {
private static final Logger log = LoggerFactory.getLogger(EndpointControlBusFileRouteBuilder.class);
private String routeId;
private String ClusterId;
public EndpointControlBusFileRouteBuilder(String routeId) {
this.routeId = routeId;
}
#Override
public void configure() throws Exception {
log.info("*** JGroups routeCluster - RouteId : " + routeId + " ***");
ClusterId = routeId + ".JGroups";
from("jgroups:" + ClusterId + "?enableViewMessages=true&channelProperties=etc/jgroups.xml")
.autoStartup(true)
.routeId(ClusterId)
.filter(dropNonCoordinatorViews())
.threads().delay(delayIfContextNotStarted(SECONDS.toMillis(5))) // run in separated and delayed thread. Delay only if the context hasn't been started already.
.log("Starting JGroups JChannel Routes Consumer!!!!!!!!!!!!!!!!!!!!!")
.to("controlbus:route?routeId=" + routeId + "&action=start&async=true");
}
}
public class EndpointControlBusProcessor implements Processor {
private String routeId = "";
private static final Logger log = LoggerFactory.getLogger(EndpointControlBusProcessor.class);
#Override
public void process(Exchange exchange) throws Exception {
List<Route> routeList = exchange.getContext().getRoutes();
ProducerTemplate template = exchange.getContext().createProducerTemplate();
for ( Route rte : routeList ) {
routeId = rte.getId();
// log.info("ROUTES: " + routeId);
// ServiceStatus routeStatus = exchange.getContext().getRouteStatus(routeId);
// log.info("Route " + routeId + " Status: " + routeStatus);
String status = template.requestBody("controlbus:route?routeId=" + routeId + "&action=status", null, String.class);
log.info("Controlbus Route Status: " + status + " for route: " + routeId);
if ( (null == status) || status.equalsIgnoreCase("Stopped") ) {
exchange.getContext().addRoutes(new EndpointControlBusFileRouteBuilder(routeId));
// status = template.requestBody("controlbus:route?routeId=" + routeId + "&action=status", null, String.class);
// log.info("Controlbus Route Status: " + status + " for route: " + routeId);
} else {
log.info("Route " + routeId + " already started");
}
}
template.stop();
}
}

How can I start and stop a timer in different classes?

I want to measure the time from the start of an incoming HTTP request and the application getting to a certain point. Both those points in time are located in different classes. How would I start and stop a timer from these different classes. I don't see a way to use 'named' timers from the MeterRegistry.
How would I go about this?
You can use AOP as below :
#Aspect
#Component
public class ControllerMonitor {
protected static final Logger LOGGER = LoggerFactory.getLogger(ControllerMonitor.class);
#Before("execution(public * com.demo.controller.*Controller.*(..))")
public void logBeforeAccess(JoinPoint joinPoint) {
if(joinPoint!=null){
String packageName = joinPoint.getSignature()!=null?joinPoint.getSignature().getDeclaringTypeName():"LOG-404";
LOGGER.info(". . .A request initiated from controller [" + packageName + "."+ getMethodSignature(joinPoint) + "]. . .");
}
}
#After("execution(public * com.demo.controller.*Controller.*(..))")
public void logAfterAccess(JoinPoint joinPoint) {
if(joinPoint!=null){
String packageName = joinPoint.getSignature()!=null?joinPoint.getSignature().getDeclaringTypeName():"LOG-404";
LOGGER.info(". . .Request from controller [" + packageName + "."+ getMethodSignature(joinPoint) + "] completed. . .");
}
}
#AfterThrowing(pointcut = "execution(public * com.demo.controller.*Controller.*(..))",throwing="exception")
public void logAfterThrowing(Exception exception){
LOGGER.error("Exception caught:"+ exception.getMessage());
}
private String getMethodSignature(JoinPoint joinPoint){
if(joinPoint!=null){
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
StringBuilder sb=new StringBuilder();
if(arguments!=null){
for (Object param: arguments) {
sb.append(param).append(",");
}
sb =(sb.length()>1)?sb.deleteCharAt(sb.length()-1):sb;
}
methodName = methodName+"("+new String(sb)+")";
return methodName;
}else{
return "LOG-405";
}
}
}
Use AOP …...No need to do changes on each class level. It will be one place config..

Pusher: Decrease timeout for connection state

I'm currently experimenting with websockets using the Pusher library for Java.
Pusher automatically changes its connection state from CONNECTED to DISCONNECTED if the internet connection is lost. However, this only seems to happen after 150 seconds of being disconnected. This is very unfortunate as in those 150s, a lot of messages can get lost, and a de facto old message can still be seen as the most up-to-date.
How can I know if the last received message is the most up-to-date? Or is there any way to decrease the timeout for the connection state?
Here is the pusher code I'm using:
import com.pusher.client.Pusher;
import com.pusher.client.channel.Channel;
import com.pusher.client.channel.ChannelEventListener;
import com.pusher.client.channel.SubscriptionEventListener;
import com.pusher.client.connection.ConnectionEventListener;
import com.pusher.client.connection.ConnectionState;
import com.pusher.client.connection.ConnectionStateChange;
public class Testing {
public static void main(String[] args) throws Exception {
// Create a new Pusher instance
Pusher pusher = new Pusher("PusherKey");
pusher.connect(new ConnectionEventListener() {
#Override
public void onConnectionStateChange(ConnectionStateChange change) {
System.out.println("State changed to " + change.getCurrentState() +
" from " + change.getPreviousState());
}
#Override
public void onError(String message, String code, Exception e) {
System.out.println("There was a problem connecting!");
}
}, ConnectionState.ALL);
// Subscribe to a channel
Channel channel = pusher.subscribe("channel", new ChannelEventListener() {
#Override
public void onSubscriptionSucceeded(String channelName) {
System.out.println("Subscribed!");
}
#Override
public void onEvent(String channelName, String eventName, String data) {
System.out.println("desilo se");
}
});
// Bind to listen for events called "my-event" sent to "my-channel"
channel.bind("my-event", new SubscriptionEventListener() {
#Override
public void onEvent(String channel, String event, String data) {
System.out.println("Received event with data: " + data);
}
});
while(true){
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
}
Just found the answer: Initiate Pusher-object with PusherOptions-object.
Here is the PusherOptions-class: http://pusher.github.io/pusher-java-client/src-html/com/pusher/client/PusherOptions.html
Here is a simple example how I decreased my connection-timeout from 150s to 15s:
// Define timeout parameters
PusherOptions opt = new PusherOptions();
opt.setActivityTimeout((long)10000L);
opt.setPongTimeout((long)5000L);
// Create a new Pusher instance
Pusher pusher = new Pusher(PUSHER_KEY, opt);
ActivityTimeout defines how often a ping is sent out to check the connectivity, PongTimeout defines the waiting time until a response from the ping-signal is expected.
The minimum ActivityTimeout is 1000ms, however such a low value is strongly discouraged by Pusher, probably to decrease the server-traffic.

JMdns ServiceListner doesn't find all services,

Hi I created sample jmdns serviceListner, When i run it , It should continue to list services as it finds, But with this my program, It list few services when run and after that it does not list any service. And i have dns-sd in my google chrome browser, So when i browse services in chrome, at that time my program list other services, Otherwise my program doesn't list services. I don't get why ServiceListner itself doesn't detect any subsequent events.
public static void main(String[] args) throws Exception {
String type = "_my-app._tcp.local.";
Enumeration<NetworkInterface> ifc = NetworkInterface.getNetworkInterfaces();
while (ifc.hasMoreElements()) {
NetworkInterface anInterface = ifc.nextElement();
if (anInterface.isUp()) {
Enumeration<InetAddress> addr = anInterface.getInetAddresses();
while (addr.hasMoreElements()) {
InetAddress address = addr.nextElement();
final JmDNS jmdns = JmDNS.create(address, type);
ServiceListenerClass aClass = new ServiceListenerClass();
jmdns.addServiceListener(type, aClass);
}
}
}
}
public static class ServiceListenerClass implements ServiceListener {
public void serviceAdded(ServiceEvent event) {
event.getDNS().requestServiceInfo(event.getType(), event.getName(), true);
}
public void serviceRemoved(ServiceEvent event) {
System.out.println((count--) + " " + event.getInfo().getName());
}
public void serviceResolved(ServiceEvent event) {
System.out.println((count++) + " :Res: " + event.getInfo().getName() + " " + event.getInfo().getPort() + " " + event.getInfo().getApplication()
+ " " + event.getInfo().getDomain() + " " + event.getInfo().getKey());
}
}
I had a similar problem two.
The problem might come from your firewall settings.
In my case the javaw.exe had access to all incoming calls but could not send anything to anyone as the firewall blocked it.
Try turning of the firewall to test you programm and to be shure thats not the firewall causing the problem.
Same issue here. Starting java with the following argument solved it for me:
-Djava.net.preferIPv4Stack=true

Problem while using springs TransactionSynchronizationManager

I am using spring TransactionSynchronizationManager.Using this manager I register a new Synchronization TransactionSynchronizationAdapter and I override the afterCompletion(int status) method of this TransactionSynchronizationAdapter .
Inside this afterCompletion the value of status must be coming as commited(0) but it is coming as active(0)
Here is the piece of code ::
TransactionSynchronizationManager
.registerSynchronization(new TransactionSynchronizationAdapter() {
public void beforeCompletion(){
int status =Status.STATUS_COMMITTED;
System.out.println("inside before completion block hurray");
}
public void afterCompletion(int status) {
System.out.println("the value of status is " + status);
System.out.println("coming after completion");
if (status == Status.STATUS_COMMITTED) {
final String memcachedKey = getMemcachedKey(pOrderId);
System.out.println("the value of memcached key is inside the aftercompletion " + memcachedKey);
mCmatesMemCachedClient.set(memcachedKey, PROVISIONING_PASS);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Tx commited. Set into memcached:Key="
+ memcachedKey + ",Value=" + PROVISIONING_PASS);
}
}
}
});
}
Don't use Status.STATUS_COMMITTED, it has nothing to do with Spring. Use TransactionSynchronization.STATUS_COMMITTED instead.

Categories

Resources