In our last part we looked at how to register a service. Now we need to work out how to lookup and use that service from another bundle.
We will put the problem in the context of our requirements, which as before are inspired by Martin Fowler's paper on dependency injection. We have built a MovieFinder as a service and registered it with the service registry. Now we want to build a MovieLister that uses the MovieFinder to search for movies directed by a specific director. Our assumption is that the MovieLister itself will be a service to be consumed by some other bundle, e.g. a GUI application. The trouble is, OSGi services are dynamic... they come and they go. That means sometimes we want to call the MovieFinder service but it just isn't available!
So, what should the MovieLister do if the MovieFinder service is not present? Clearly the call to the MovieFinder is a critical part of the work done by MovieLister , so there only a few choices available to us:
1. Produce an error, e.g. return null or throw an exception.
2. Wait.
3. Don't be there in the first place.
In this article we're going to look at the first two options, as they are quite simple. The third option may not even make any sense to you yet, but hopefully it will after we look at some of the implications of the first two.
The first thing we need to do is define the interface for the MovieLister service. Copy the following into osgitut/movies/MovieLister.java :
package osgitut.movies;
import java.util.List;
public interface MovieLister {
List listByDirector(String name);
}
Now create the file osgitut/movies/impl/MovieListerImpl.java :
package osgitut.movies.impl;
import java.util.*;
import osgitut.movies.*;
import org.osgi.framework.*;
import org.osgi.util.tracker.ServiceTracker;
public class MovieListerImpl implements MovieLister {
private final ServiceTracker finderTrack;
public MovieListerImpl(ServiceTracker finderTrack) {
this.finderTrack = finderTrack;
}
public List listByDirector(String name) {
MovieFinder finder = (MovieFinder) finderTrack.getService();
if(finder == null) {
return null;
} else {
return doSearch(name, finder);
}
}
private List doSearch(String name, MovieFinder finder) {
Movie[] movies = finder.findAll();
List result = new LinkedList();
for (int i = 0; i < movies.length; i++) {
if(movies[i].getDirector().indexOf(name) > -1) {
result.add(movies[i]);
}
}
return result;
}
}
This is probably our longest code sample so far! So what's going on here? Firstly you notice that the logic of actually searching for movies is separated into a doSearch(String,MovieFinder) method, to help us isolate the OSGi-specific code. Incidentally, the way we're performing the search is pretty stupid and inefficient, but that's not really important for the purposes of the tutorial. We only have two movies in our database anyway!
The interesting part is in the listByDirector(String name) method, which uses a ServiceTracker object to obtain a MovieFinder from the service registry. ServiceTracker is a very useful class which abstracts away a lot of unpleasant detail in the lowest levels of the OSGi API. However we still have to check whether the service was actually present. We assume that the ServiceTracker will be passed to us in our constructor.
Note that you may have seen elsewhere code that retrieves a service from the registry without using ServiceTracker . For example, it is possible to use the getServiceReference and getService calls on BundleContext . However the code you have to write is quite complex and it has to be careful to clear up after itself. In my opinion, there is very little benefit in dropping down to the low level API, and lots of problems with it. It's better to use ServiceTracker almost exclusively.
A good place to create a ServiceTracker is in the bundle activator. Copy this code into osgitut/movies/impl/MovieListerActivator.java :
package osgitut.movies.impl;
import java.util.*;
import org.osgi.framework.*;
import org.osgi.util.tracker.ServiceTracker;
import osgitut.movies.*;
public class MovieListerActivator implements BundleActivator {
private ServiceTracker finderTracker;
private ServiceRegistration listerReg;
public void start(BundleContext context) throws Exception {
// Create and open the MovieFinder ServiceTracker
finderTracker = new ServiceTracker(context, MovieFinder.class.getName(), null);
finderTracker.open();
// Create the MovieLister and register as a service
MovieLister lister = new MovieListerImpl(finderTracker);
listerReg = context.registerService(MovieLister.class.getName(), lister, null);
// Execute the sample search
doSampleSearch(lister);
}
public void stop(BundleContext context) throws Exception {
// Unregister the MovieLister service
listerReg.unregister();
// Close the MovieFinder ServiceTracker
finderTracker.close();
}
private void doSampleSearch(MovieLister lister) {
List movies = lister.listByDirector("Miyazaki");
if(movies == null) {
System.err.println("Could not retrieve movie list");
} else {
for (Iterator it = movies.iterator(); it.hasNext();) {
Movie movie = (Movie) it.next();
System.out.println("Title: " + movie.getTitle());
}
}
}
}
Now this activator is starting to look interesting. Firstly in the start method it creates a ServiceTracker object, which is used by the MovieLister we just wrote. It then "opens" the ServiceTracker which tells it to start tracking instances of the MovieFinder service in the registry. Then it creates our MovieListerImpl object and registers it in the service registry under the interface name "MovieLister" . Finally, just for the sake of being able to see something interesting when we start the bundle, the activator runs a simple search against the MovieLister and prints the result.
We need to build and install this bundle. I'm not going to give full instructions this time -- you should be able to refer back to the previous installments and work it out. Remember you also need to create a manifest file, and it has to refer to the osgitut.movies.impl.MovieListerActivator class as its Bundle-Activator . Also your Import-Package line needs to include the three packages that we're importing from other bundles, namely org.osgi.framework , org.osgi.util.tracker and osgitut.movies .
Once you have installed MovieLister.jar into the Equinox runtime, you can start it. At that point you will see one of two messages, depending on whether the BasicMovieFinder bundle is still running from last time. If it's not running you will see:
osgi> start 2
Could not retrieve movie list
However if it is running you will see following:
osgi> start 2
Title: Spirited Away
By stopping and starting each bundle, you should be able to get either message to appear at will. And that is almost all for this installment, except remember I said that one of the things you can do when a service is not available is to wait for it? With the code we already have, this is actually trivial: simply change line 16 of MovieListerImpl to call waitForService(5000) on the ServiceTracker instead of getService() , and add a try/catch block for the InterruptedException .
This will cause the listByDirector() method to hang for up to 5000 milliseconds waiting for the MovieFinder service to appear. If a MovieFinder service is installed in that time -- or, of course, if it was already there -- then we will immediately get it an be able to use it.
Generally though I would advise against suspending threads like this. Particularly in this case, it could be dangerous because the listByDirector() method is actually called from the start method of our bundle activator, which was called from a framework thread. Activators are meant to return quickly, because a number of other things need to happen when a bundle is activated. In fact in the worst case we could cause a deadlock, because we are effectively entering a synchronized block on an object owned by the framework, which might already by locked by something else. The general guideline is never perform any long-running or blocking operations in a bundle activator start method, or in any code called directly from the framework.
In the next installment we will take a look at the mysterious third option for dealing with absent dependencies: "Don't exist in the first place". Stay tuned!
分享到:
相关推荐
深入理解OSGi:Equinox原理、应用与最佳实践.pdfOSGi应用开发
NULL 博文链接:https://zhouwendong006.iteye.com/blog/381680
NULL 博文链接:https://zhouwendong006.iteye.com/blog/408415
NULL 博文链接:https://zhouwendong006.iteye.com/blog/382882
深入理解OSGi:Equinox原理、应用与最佳实践源代码,同时附带equinox-SDK-3.8源代码。
深入理解OSGi:Equinox原理、应用与最佳实践,书本源代码
深入理解OSGi:Equinox原理、应用与最佳实践源码
《深入理解OSGi:Equinox原理、应用与最佳实践》自从1999年OSGi联盟成立以来,OSGi技术随着Java一起飞速发展,它已经成为一种被广泛认可的软件架构技术和方法,许多世界著名的IT企业都加入到OSGi的阵营之中,OSGi...
《深入理解OSGi:Equinox原理、应用与最佳实践》一书的附赠光盘
《深入理解OSGi:Equinox原理、应用与最佳实践》共14章,分4个部分。第一部分(第1 章):走近OSGi,主要介绍了什么是OSGi以及为什么要使用OSGi。第二部分(第2~4章):OSGi规范与原理,对最新的OSGi R5.0中的核心...
《深入理解OSGi:Equinox原理、应用与最佳实践》,作者周志明 / 谢小明,本书是原创Java技术图书领域继《深入理解Java虚拟机》后的又一实力之作,也是全球首本基于最新OSGi R5.0规范的著作。
OSGi的开发和部署方式,方便部署和演示
《Eclipse RCP与Spring OSGi:技术详解与最佳实践》由资源的Eclipse专家亲自执笔,并得到了Eclipse官方技术社区的强烈推荐,权威性毋庸置疑!内容全面,系统讲解了利用Eclipse RCP和Spring OSGi开发大规模Java应用的...
全面解读OSGi规范,深刻揭示OSGi原理,详细讲解OSGi服务,系统地介绍Equinox框架的用法,并通过源代码分析其工作机制,包含大量可操作性极强的解决方案和最佳实践。
Building Modular Cloud Apps with OSGi
Getting Started with OSGi 教你如何开发OSGi服务.
NULL 博文链接:https://springsfeng.iteye.com/blog/1259203