Application of Servicelistener of OSGi

Source: Internet
Author: User
application of Servicelistener of OSGi Preface

I was going to skip the basics of these OSGi directly, starting with some intermediate or advanced articles in OSGi applications, and then think of Servicelistener, Servicetracker, ds in OSGi, and all that needs to be said, So decided to osgicommand follow-up content, from Servicelistener began to talk about, but here will no longer tell the Felix official website of the Servicelistener example, Instead, they write example and explain them separately. Servicelistener

/**
 * A {@code serviceevent} listener. {@code Servicelistener} is a
 * listener interface This may being implemented by a bundle developer. When a
 * {@code serviceevent} are fired, it is synchronously delivered to a
 * {@code servicelistener}. The Framework may deliver
 * {@code serviceevent} objects to a {@code Servicelistener} out * of order and may
 Concu Rrently call and/or reenter a
 * {@code servicelistener}.
 * 
 */

Servicelistener explanation as shown above, the original meaning is this is just an interface, after the corresponding implementation, can be used to monitor certain services, in the service registration, modification, cancellation, the corresponding other calls, now I will tell the specific use of this servicelistener, In the course of use, again to explain the problems in the middle. Servicelistener Usage 1

First provide an interface and an implementation class, respectively, HelloService and Helloserviceimpl, the code is as follows:

HelloService:

Package cn.com.example;

/**
 * Created by Xiaxuan on 16/7/12.
 *
/public interface HelloService {

    string hello (string name);
}

Helloserviceimpl:

Package cn.com.example;

/**
 * Created by Xiaxuan on 16/7/12.
 *
/public class Helloserviceimpl implements HelloService {public

    string Hello (string name) {return
        " Hello "+ name;
    }
}

is very simple, is to provide a simple service, one of the methods for Hello, the real focus or in the activator, now put the code in the activator, and then to explain the listening service and the problem of easy to occur:

Package cn.com.example;

Import org.osgi.framework.*;
 /** * Created by Xiaxuan on 16/7/12.
    * * Public class Activator2 implements Bundleactivator, Servicelistener {serviceregistration serviceregistration;


    Bundlecontext context;
        public void Start (Bundlecontext context) throws Exception {This.context = context;
        Context.addservicelistener (this);
        SYSTEM.OUT.PRINTLN ("Service registered ...");
    Serviceregistration = Context.registerservice (Helloservice.class, New Helloserviceimpl (), NULL);
        public void Stop (Bundlecontext context) throws Exception {Context.removeservicelistener (this);
        SYSTEM.OUT.PRINTLN ("Service unregistered ...");
    Serviceregistration.unregister (); public void Servicechanged (Serviceevent event) {switch (Event.gettype ()) {case SERVICEEVENT.R Egistered://Get service reference ServiceReference ref = Context.getservicereference (HelloService. CLASS);
                Get Service instance HelloService HelloService = (helloservice) context.getservice (ref); if (HelloService!= null) {//Invoke service method System.out.println (Helloservice.hello ("x
                    Iaxuan "));
                Release service Context.ungetservice (ref);
            } break;
                Case ServiceEvent.UNREGISTERING:System.out.println ("servicechanged Find service unregistered.");
        Break
 }
    }
}

After we implement Servicelistener in activator, we also need to add ourselves to the listener, in the Servicechanged method, when the service changes, you can listen to it in this method, or register, log off, Or changes can be made to monitor, now we hit the breakpoint, listening to related services. service startup

The start of the service is no longer screenshots, this time we in the stop bundle, and then start bundle again to debug and view the corresponding information, now show Karaf has successfully started the screenshot, as follows:

Can see example this bundle has been normal start, now first use the Stop command, essentially in Karaf this command is Bundle:list command, in the Karaf a large number of the use of the command, in the later if there is time will tell the source of the Karaf, talk about these orders , this time the example ID is 8, we use Stop 8 to stop this bundle, after executing the command as follows :

When the state in the bundle is resolved, the bundle has stopped, and then we start the bundle and the command is start 8, where we observe our breakpoint, which is set in the Servicechanged method, As shown below:

We let go of the breakpoint, and this time the program enters the breakpoint again, as follows:

Found this time to enter the breakpoint, the event type and the last difference, stating that here's the Servicelistener Servicechange method for the current bundle start of the hand, all the service registration has been done listening, this time, we remove breakpoints, observe the console, Will find many times the ' Hello Xiaxuan ', as follows:

Five times the Hello Xiaxuan, indicating that there are five service registrations, each service registration has come in to obtain a helloservice, and then call a service, in the console print once, Servicelistener and no specific service to monitor. Servicelistener Usage 2

In the above Servicelistener usage, and not only in activator to implement Servicelistener to do the listening service, can be implemented directly in the Start method, if the Activator class implements the Servicelistener interface , you need to add it to the listener code as follows:

Context.addservicelistener (this);

If implemented in the Start method, the code looks like this:

Package cn.com.example;

Import org.osgi.framework.*;
 /** * Created by Xiaxuan on 16/7/13.
    * * Public class Activator3 implements Bundleactivator {serviceregistration serviceregistration;


    Bundlecontext context;
        public void Start (Bundlecontext bundlecontext) throws Exception {this.context = Bundlecontext;
        SYSTEM.OUT.PRINTLN ("Service registered ...");
        Serviceregistration = Context.registerservice (Helloservice.class, New Helloserviceimpl (), NULL);
                Context.addservicelistener (New Servicelistener () {public void servicechanged (Serviceevent event) {
                        Switch (Event.gettype ()) {case serviceevent.registered://Get Service Reference
                        ServiceReference ref = Context.getservicereference (Helloservice.class);
                        Get Service instance HelloService HelloService = (helloservice) context.getservice (ref); if (heLloservice!= null) {//Call service method System.out.println (Helloservic
                            E.hello ("Xiaxuan"));
                        Release service Context.ungetservice (ref);
                    } break; 
                        Case ServiceEvent.UNREGISTERING:System.out.println ("servicechanged Find service unregistered.");
                Break
    }
            }
        });
        public void Stop (Bundlecontext context) throws Exception {System.out.println ("service unregistered ...");
    Serviceregistration.unregister ();
 }
}

The new Servicelistener directly in the Addservicelistener, and then implement the relevant methods, compared to the simpler, but the implementation of the same effect. Summary

When using Servicelistener, only when the service is related to changes in the cost of acquisition, you can dynamically perceive service registration and cancellation.

But the problem is that the service that existed before Servicelistener registration is unable to monitor, it needs to maintain the acquisition and release of the service, and it is inconvenient if you need to monitor multiple service.

As long as the service is changed when the relevant monitoring, in fact, many times without listening to other services, sometimes use up more trouble.

The next section will explain the Servicetracker, which is a further encapsulation of servicelistener, which can effectively monitor the services we need.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.