当前位置:网站首页>[turn]: OSGi specification in simple terms
[turn]: OSGi specification in simple terms
2022-07-05 05:14:00 【morpheusWB】
OSGI standard Explain profound theories in simple language
One 、OSGI brief introduction
1、OSGI brief introduction
OSGI(Open Service Gateway Initiative), Open service gateway protocol , It's for Java Dynamic model system of .
OSGI Means by OSGI Alliance Made by the organization Java Modular specification ,OSGI The core of the specification is a framework , It defines the application's lifecycle pattern and service registration . be based on OSGI The framework defines a large number of OSGI service : journal 、 Configuration Management ,HTTP service ( function Servlet)、XML analysis 、 Device access 、 Package management 、 License management 、 User management 、IO Connect 、Jini and UPnP etc. .
OSGI The Chinese community :http://www.osgi.com.cn/
OSGI Official website :https://www.osgi.org/
OSGI The framework implements an elegant 、 A complete and dynamic component model , Components (bundle) Can be installed remotely without rebooting 、 start-up 、 Upgrade and uninstall .
OSGI The service platform provides the function of dynamically changing the structure on a variety of network devices without restart .
To minimize coupling and make coupling manageable ,OSGI Technology provides a service-oriented architecture , Make components dynamically discover each other .
OSGI The alliance has developed such as HTTP The server 、 To configure 、 journal 、 Security 、 User management 、XML And many public function standard component interfaces . The compatibility plug-in implementation of standard components can be obtained from different computer service providers .
OSGi Our main responsibility is to enable developers to create dynamic 、 Modular Java System .
2、OSGI The composition of the specification
OSGI Specifications include the following sub specifications :
A、Framework standard (OSGI The core , Provide a secure and manageable Java Framework To deploy scalable Java service )
B、Package Admin Service standard ( Manage different Bundle Reference relationship between . When Bundle When updating or uninstalling, determine whether other services are using the current Bundle)
C、Start Level standard ( Defines a start and stop OSGi Service Platform when , Different Bundles The sequence of starting or stopping )
D、Permission Admin Service standard (Bundle Is it allowed to execute another Bundle Code for )
E、URL Handlers Service standard ( How to register URL Schema, How to integrate java.io.InputStream Object to a specific Java object )
F、Log Service standard
G、Configuration Admin Service standard
H、Device Access Specification
I、User Admin Service Specification
J、IO Connector Service Specification
K、Http Service Specification
L、Preference Service Specification
M、Wire Admin Service Specification
N、XML Parser Service Specification
O、Metatype Specification
P、Service Tracker Specification
Q、Measurment and State Specification
R、Position Specification
S、Execution Environment Specfication
3、OSGI The advantages of
OSGI Its advantages are mainly shown in the following aspects :
A、 Hot pluggable plug-in architecture
be based on OSGI Your application can dynamically change its running state and behavior . stay OSGI In the frame , Each component is hot pluggable , therefore , Modifications to a particular component do not affect all components in the container , Most components in operation can still work as usual , Deploy a new Bundle There is no need to restart the server .
B、 Reusability
OSGI The framework itself is highly reusable , It is easy to build a truly interface oriented program architecture , Every component (Bundle) It is an independent reusable unit . be based on OSGI Unique characteristics , During enterprise development , For new development , Reusable modules can be simplified from the component library of the enterprise , Tailor new components , Maximize the use of existing resources , Reduce development costs , Enhance the competitiveness of enterprises .
C、 Efficiency , stability
OSGI It is a stable and efficient system .OSGI As a micronucleus system , Its core is only a few JAR package . be based on OSGI The low coupling of the system of the framework , The advantages of its structure ensure that a specific component will not affect the overall situation , It will not lead to the collapse of the global system due to local errors .
4、OSGI The shortcomings of
A、 Each component (Bundle) Are loaded by a separate class loader , With some Java EE It is difficult to integrate the frameworks that are used more in the project , Such as Spring MVC、Struts2 etc. .
B、 at present OSGI The management end provided by the framework is not strong enough , Now the management side only provides basic component state management 、 Log view and other functions , Like dynamically modifying system level configuration (config.ini)、 Dynamically modify the configuration of components (Manifest.mf)、 Functions such as startup level have not been provided .
C、 use OSGI As a standard module development 、 The deployment mode naturally puts forward new requirements for existing developers , Need to learn new ones based on OSGI Development mode .
Two 、OSGI Frame principle
1、OSGI Introduction to the framework
OSGI The framework can be conceptually divided into three layers : Module layer 、 Life cycle layer and service layer .
Module Layer: The module layer mainly involves packages and shared code ;
Lifecycle Layer: The lifecycle layer mainly involves the runtime lifecycle management of components ;
Service Layer: The service layer mainly involves the interaction and communication between modules .
OSGI Framework yes OSGI Service Platform The core component of the specification , Provides a generic 、 Safe and manageable Java framework. adopt OSGI Framework It can support a kind of component Service application Deployment and expansion of .
OSGI Compatible devices can be downloaded and installed OSGI Components , It can also be deleted once it is no longer needed . A certain number of components will be registered after installation Services, And by the same Framework Other components under .
In a dynamically extended OSGI Environment ,Framework Manage the installation and update of components , It also manages components and Services Dependencies between .
Framework Provide the necessary resources for component developers to Java Development on the platform , It provides the function of code dynamic loading for the developed components , It also enables developers to develop 、 Deploy a large-scale Services It's easy to change .
secondly ,Framework by Java Component developers provide a concise and consistent programming model , Simplifies the complexity of development deployment . The programming model allows developers to bind their interface specifications to OSGI In the environment Service.
A consistent programming model helps developers cope with some critical errors that can be estimated .Framework Will run on different hardware environments , But a consistent interface ensures that components can run on a consistent service interface .
2、 Module layer
The module layer is OSGi The most basic part of the framework .
OSGi The modular , Is through for Jar Package addition metadata To define which classes should be exposed , Which classes should be hidden , Its control unit is called component Bundle(jar package ).
Bundle In order to jar A modular physical unit in the form of a package , Include code 、 Resource files and metadata (metadata), also jar The physical boundary of the package is also the encapsulation boundary of the runtime logic module .
Bundle yes OSGi The basic components of , Its manifestation is still Java Traditional in concept Jar package .
adopt META-INF In the catalog MANIFEST.MF It is further defined in the document .
Usually a MANIFEST.MF The contents of the document are as follows :
Manifest-Version: 1.0Bundle-ManifestVersion: 2Bundle-Name: UtilBundle-SymbolicName: com.ibm.director.la.utilBundle-Version: 1.0.0Bundle-RequiredExecutionEnvironment: J2SE-1.5Import-Package: org.osgi.framework;version="1.3.0"Export-Package: com.ibm.director.la.util;uses:="org.osgi.framework"Bundle-ClassPath: lib/junit.jar,
MANIFEST.MF File storage is actually Bundle Metadata .
The content of metadata can be precisely defined Bundle All kinds of characteristics of , At the same time, it can be better for Bundle Identify and help users identify Bundle To understand .
3、 Life cycle layer
The life cycle layer is OSGi The framework belongs to the layer above the module layer , The operation of the lifecycle layer is based on the function of the module layer .
The main function of the lifecycle layer is to control dynamic installation 、 Turn on 、 close 、 Update and uninstall components .
The lifecycle layer can manage applications externally or establish applications that can manage themselves ( Or a combination of the two ), And it gives the application itself great dynamics .
Bundle The use of requires the lifecycle layer API And OSGi The lifecycle layer of the framework interacts .
4、 Service layer
OSGi The service is registered to OSGi One of the frames Java object . When registering, you can set Service Properties of . And getting Service You can filter according to the attributes .
Bundle Can pass Bundle Context to register Service Or go to query Service.
3、 ... and 、 Module layer
1、 Modular Introduction
Modularity is the decomposition of a large system into several smaller logical units that cooperate with each other , Improve the maintainability and encapsulation of the system by forcing the logical boundaries between modules .
modular (module) Defines a logical boundary , The module itself precisely controls which classes are completely encapsulated , And which classes need to be exposed for external use . Developers can easily shield the implementation inside the module , Will public API Exposed to the outside .
2、OSGI Modularity and object orientation
In object-oriented programming, not all functions are crammed into the same class . Object oriented programming finds many things from the problem domain , Each thing is responsible for different functions , Try to achieve high cohesion and low coupling . Object oriented modularity granularity is at the class level .
OSGi Modularization of is achieved by JAR Package addition metadata To define which classes should be exposed and which classes should be hidden in the package , The granularity of controlling visibility is in components (JAR package ) On the level of .
OSGI The ability brought by modularity and object-oriented thinking is to ensure high cohesion and low coupling by controlling visibility and availability , But the granularity is different , One is at the component level , One is at the object level .
3、JAVA Limitations in modularity
A、 Visibility control of underlying code
Java Provides private、public、protected and package private( No modifiers ) Four levels of access control , Provides the underlying OO Data encapsulation features .Packege It has the function of dividing code , But if the code in the package is to be visible outside the package , Must be set to public(protected, Using inheritance ).
org.serc.helloworld.Hello.java: An interface is defined
package org.serc.helloworld; public interface Hello { void sayHello(); }
org.serc.helloworld.impl.HelloImpl.java: Realized Hello Interface
package org.serc.helloworld.impl;import org.serc.helloworld.Hello;public class HelloImpl implements Hello{ final String helloString; public HelloImpl(String helloString){ this.helloString = helloString; } public void sayHello(){ System.out.println(this.helloString); }}
org.serc.helloworld.main.Main.java file :
package org.serc.helloworld.main;import org.serc.helloworld.Hello;import org.serc.helloworld.HelloImpl;public class Main{ final String helloString; public static void main(String[] args){ Hello hello = new HelloImpl(“Hello,SERC!”); hello.sayHello(); }}
The three files are in different packages .HelloImpl Implementation details should not be exposed to other packages , But from Main.java Of main As can be seen from the method , In order to create Hello Example , Must introduce HelloImpl class , however HelloImpl As the implementation details of the interface , It should not be exposed to users , It violates the principle of encapsulation .
If you don't want HelloImpl Exposed , Extra work needs to be done to ensure that the implementation details are hidden , You can simply create an implementation Hello An instance of an interface . There are many ways ( For example, factory mode ) To achieve , But it adds redundant work unrelated to the function of the application itself , yes Java Limitations .
B、classpath Limitations
stay classpath Add jar When the package , Only the file path is given , and jar The version of the package 、 Uniformity 、 Dependence , Cannot be in classpath Or from classpath See the corresponding properties .
classpath Medium jar Packages are loaded sequentially , for example :
classpath=/servlet2.2/servlet.jar;/servlet2.3/servlet.jar, In the process of practical application ,Java Use servlet2.2, instead of servlet2.3. If the team develops separately in a large system , Use your own servlet package , And the version number is different , When the development results are finally merged , Which version is used servlet It's hard to figure it out .
Even if classpath Can you notice the problem of the version , There is no way to pinpoint dependency . Developers need to add dependent packages according to the prompt , Until the virtual machine does not run until the package shortage exception .
C、OSGI Yes JAVA Limited improvements
OSGi It's easy to solve JAVA The limitations of :
Package visibility :OSGi By introducing the visibility mechanism of packages , It can completely control which modules the code in a package is visible to , Not limited to undifferentiated visibility , Thus, it improves Java Code access control mechanism .
The version of the package :OSGi By adding version information to the package , Can precisely control the dependence of code , Ensure the version consistency of the code , Make up for classpath The shortcomings of .
4、 Components Bundle brief introduction
Components (bundle) In order to jar A modular physical unit in the form of a package , Contains code 、 Resource files and metadata (metadata), also jar The physical boundary of the package is also the encapsulation boundary of the runtime logic module .
In standard jar Bag manifest Add some components to the file (bundle) Modularity of (metadata) after ,jar The bag becomes a bundle.
bundle And the general jar The biggest difference between packages is metadata .
Bundle The purpose of metadata is to accurately describe modular related bundle features , Give Way OSGi Frame pair bundle Carry out various processing work ( For example, dependency resolution , Forced encapsulation, etc ), Metadata mainly has three parts :
A、 Readable information ( Optional )
OSGi The standard defines several metadata entries to help better understand and use bundle, But all items are not necessary , And it will not have any impact on the modularity ,OSGi The framework completely ignores readable information .
Bundle-Name: SERC HelloworldBundle-Vendor: GR, SERCBundle-DocURL: http://elevenframework.orgBundle-Category: exampleBundle-Copyright: SERC
B、bundle identifier ( must )
bundle Identifiers are used to uniquely identify a bundle.
In the early OSGi The standard does not provide a known bundle Methods , until OSGi R4 standard ,“ only bundle identifier ” To be mentioned . For backward compatibility ,Bundle-Name Cannot be used as an identifier , Otherwise, it will increase the work of maintaining backward compatibility , So use new manifest attribute Bundle-SymbolicName.
Bundle-SymbolicName: org.serc.helloworld
Bundle-Name It's for users , and Bundle-SymbolicName It's for OSGi The frame reads , Give Way OSGi The framework can uniquely identify a bundle.
Just one Bundle-SymbolicName It must be able to uniquely identify one bundle, But over time ,bundle There may be a new version , Adding version attributes will make bundle More accurate information .
Bundle-Name: SERC HelloworldBundle-Vendor: GR, SERCBundle-DocURL: http://elevenframework.orgBundle-Category: exampleBundle-Copyright: SERC
C、 Code visibility ( must )
Code visibility is used to define internal and external code . stay JavaSE Medium jar If the bag is placed classpath in , that jar Yes classpath All programs under are visible , And visibility cannot be changed . and OSGi The standard defines the following attributes to describe the visibility of code :
Bundle-ClassPath: Defines the formation bundle Where all the code of ,Java Medium classpath It's defined jar The location of the package , and Bundle-ClassPath Property describes bundle The inner class is in bundle In the path . for example :
Bundle-ClassPath:.,other-classes/,embedded.jar
Export-Package: Explicit exposure needs and others bundle Shared code , Each package is separated by commas , Each package can use modifiers to modify other features of the package .
Export-Package: org.serc.hellworld; vendor=”SERC”,org.serc.hellworld.impl; vendor=”Gou Rui”
Import-Package: Definition bundle Dependent external code , Its format and Export-Package identical , And you can also use modifiers to modify packages . Modifiers are used to limit the scope of dependent packages , It's like a filter , Not like Export-Package Is used to declare the characteristics of the package . for example :
Import-Package: org.serc.helloworld; vendor=”SERC”
Four 、 Life cycle layer
1、 Introduction to lifecycle layer
The life cycle layer is OSGi The framework belongs to the layer above the module layer , Its operation is based on the function of the module layer . The main function of the lifecycle layer is to enable developers to manage applications from the outside or establish applications that can manage themselves ( Or a combination of the two ), And give the application itself great dynamics .
2、 Introduction to life cycle management
Generally speaking , Program ( Or part of the program ) Must obey some kind of life cycle . The life cycle of software has 4 A typical stage , as follows :
If you are creating an application , First install (install) application ; When all the dependencies of the application are satisfied , Applications can be executed ; If the application no longer needs , You can stop (stop); After a while , It may need to be updated (update) Version of the application ; Final , It may be removed (remove) application .
By operating the application externally or internally , Complete the application lifecycle management process . For non modular applications , The operation is aimed at the whole application ; For modular applications , There can be finer granularity ( For a module in the application ) Life cycle management of .
3、OSGi bundle Life cycle
To use components (bundle), You have to use the life cycle layer API And OSGi The lifecycle layer of the framework interacts .
OSGi The core of the framework does not force the use of any specific API Interaction mechanism ( Like the command line ,GUI, perhaps XML Configuration files, etc ), It's just simple Java API nothing more , Developers can create their desired interaction patterns at will , Ensure the flexibility of the framework .
In standard Java Programming , Will pass will jar Put the bag in classpath To use jar package , and bundle Different .Bundle Only when installed (install) To a OSGi It can only be used in the running instance of the framework , also OSGi The framework supports bundle Complete lifecycle management , And support these management operations to complete in the application execution , Its dynamics can be seen .
Bundle The state transition diagram of the life cycle is as follows :
Can pass Bundle Of getState How to get bundle Current state .
Starting and Stopping The state is transient , After a while, it will automatically move to the next state , No transfer conditions are required .
4、 Life cycle layer API
Lifecycle layer API Mainly by BundleActivator、BundleContext、Bundle Three core interfaces .
A、BundleActivator
BundleActivator Allow developers to capture bundle Of start and stop event , And make a customized response to .
BundleActivator The interface of is defined as follows :
public interface BundleActivator { public void start(BundleContext context) throws Exception; public void stop(Bundlecontext context) throws Exception;}
If a class implements BundleActivator Interface , Then the class becomes a Activator. But implementation is not enough , Must let OSGi The framework knows Activator The existence of . So it needs to be in MANIFEST Add the following attribute to the file :
Bundle-Activator:org.demo.Activator
When bundle start-up (start) When ,OSGi The framework will call Activator Of start Method , The same applies to stop Method .
Not every bundle You need one activator, occasionally bundle Just to be with others bundle Share code , There is no need to make redundant actions when starting and stopping . Whether to use BundleActivator excuse , Need specific analysis .
B、BundleContext
BundleContext yes bundle Execution time context in the framework , Provides a way to interact with the framework .
BundleContext Methods in interfaces are mainly divided into two categories , One is related to deployment and lifecycle management , The other is about using the service layer bundle Methods of interaction between .
public interface BundleContext { String getProperty(String key); Bundle getBundle(); Bundle installBundle(String location, InputStream input) throws BundleException; Bundle installBundle(String location) throws BundleException; Bundle getBundle(long id); Bundle[] getBundles(); void addBundleListener(BundleListener listener); void removeBundleListener(BundleListener listener); void addFrameworkListener(FrameworkListener listener); void removeFrameworkListener(FrameworkListener listener);}
BundleContext The interface is for its related bundle Is the only execution context , And only in bundle It belongs to active The context is meaningful when the state is executed , That is to say start Methods are called and stop Between two points in time when the method is called . If one bundle Not in active Period of time , But the components bundlecontext Object is used , The framework throws an exception .
The framework also uses this context object for bundle Security and resource allocation , therefore BundleContext Objects should be treated as private objects , Should not be casually in bundle Passed between .
C、Bundle
Bundle Logically, it represents a bundle,OSGi A physics in the environment bundle Corresponding to one bundle object .bundle Object contains bundle Basic information and bundle Declare the control interface of the cycle .
stay BundleContext Interface ,getBundle Method can get Bundle object .
For each installed in the frame bundle, Frameworks create one Bundle Objects logically express .Bundle Interface defined bundle Life cycle management approach :
public interface Bundle { BundleContext getBundleContext(); long getBundleId(); Dictionary getHeaders(); Dictionary getHeaders(String locale); String getLocation(); int getState(); String getSymbolicName(); Version getVersion(); void start(int options) throws BundleException; void start() throws BundleException; void stop(int options) throws BundleException; void stop() throws BundleException; void update(InputStream input) throws BundleException; void update() throws BundleException; void uninstall() throws BundleException;}
Most of the OSGi The implementation of the framework will locatioin Interpreted as pointing to OSGi bundle One of the URL, It will pass when necessary URL take bundle Download to the framework to install and use . but OSGi The standard does not specify location The form of must be URL, and URL It is not necessary , You can also use the input stream (Input Stream) To install bundle.
bundle You can't change your state by yourself , Like a active Of bundle You can't stop own ,stop You will throw an exception .
5、 ... and 、 Service layer
1、 Service profile
Service is a contract between service provider and service consumer . Users generally don't care about the details of service implementation , Only care about whether the contract is satisfied ( What functions should the service provide , What format does it meet ). The process of using services includes the form of discovering services and reaching agreements , We need to find the corresponding service through the symbolic characteristics of the service .
2、OSGI Service layer
The service layer is OSGi The top layer in the frame , The service layer brings more dynamics , And use the service-oriented programming model . When one bundle Find and start using OSGi After a service in , Services can change or disappear at any time .
OSGi The framework has a centralized registry , Registry compliance publish-find-bind Model :
A service provider bundle You can publish POJO As a service entity ; A user of services bundle You can find and bind services through the registry .
Can pass BundleContext Interface to complete the release of services 、 Find out 、 binding , as follows :
public interface BundleContext { void addServiceListener(ServiceListener listener, String filter) throws InvalidSyntaxException; void addServiceListener(ServiceListener listener); void removeServiceListener(ServiceListener listener); ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties); ServiceRegistration registerService(String clazz, Object service, Dictionary properties); ServiceRegistration[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException; ServiceRegistration[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException; ServiceReference getServiceReference(String clazz); Object getService(ServiceReference reference); boolean ungetService(ServiceReference reference); }
3、 Publishing services
In order to make others bundle Can discover services , It must be characterized before publishing the service . Service features include the name of the interface ( It can be an array of names ), Interface implementation and an optional java.util.Dictionary Metadata information of type . Examples are as follows :
String[] interfaces = new String[]{StockListing.class.getName(), StockChart.class.getname()}; Dictionary metadata = new Properties(); metadata.setProperty("name", "LSE"); metadata.setProperty("currency", Currency.getInstance("GBP")); metadata.setProperty("country", "GB"); ServiceRegistration registration = bundleContext.registerService(interfaces, new LSE(), metadata);
In the above code , adopt ServiceRegistration Object can update the metadata of the service :
registration.setProperties(newMetadata);
You can log off the service directly :
registration.unregister();
ServiceRegistration Objects cannot be compared with other Bundles share , because ServiceRegistration Objects and publishing services bundle The life cycle of is interdependent . If bundle It no longer exists in the framework execution environment , that ServiceRegistration Objects should not exist .
Parameters in the code new LSE() It's a POJO, There is no need to implement any OSGi Type or use annotation , As long as the service agreement is met .
If before deleting the published service bundle And stop , The framework will help delete Services .
4、 The discovery service
You can find the correct service from the registry according to the service contract . The interfaces for discovering services and obtaining their references are as follows :
ServiceReference reference = bundleContext.getServiceReference(StockListing.class.getName());
reference Is an indirect reference to the service object , The purpose of not using service objects directly is to decouple the use of services from the implementation of services , Use the service registry as the intermediary between the two , Achieve the purpose of tracking and controlling services , At the same time, users can also be notified after the service disappears .
ServiceReference Can be in bundle Enjoy each other , With the use of services bundle The life cycle of .
stay getServiceReference In the method , choice service The default priority of is to select service.rank The highest , stay rank In the case of equality, select the earliest registered in the framework . In addition to the default rules , You can also do it in getServiceReferences By adding filter parameters ( As the second parameter to call the method ) To do some screening .
ServiceReference[] references = bundleContext.getServiceReferences(StockListing.class.getName(), "(&(currency=GBP)(objectClass=org.example.StockChart))");
The matching parameter is a string , The format of the string belongs to LDAP Query format , stay RFC1960 There is a complete description in the standard .
The content to the left of the equal sign in the string is metadata (Dictionary) Left value in , Match the right value corresponding to the left value with the metadata of the service . Examples of matching are as follows :
Attribute matching :
(name=John Smith) (age>=20) (age<=65)
Fuzzy matching :
(name~=johnsmith)
Wildcard match :
(name=Jo*n*Smith*)
Determine whether an attribute exists :
(name=)
Conditions and :
(&(name=John Smith)(occupation=doctor))
Condition or :
(|(name~=John Smith)(name~=Smith John))
* Conditional non : **
(!(name=John Smith))
5、 Bind and use services
After discovering the service , Before using the service , The implemented service must be bound from the registry .
StockListing listing = (StockListing) bundleContext.getService(reference);
Back to POJO The instance and the instance registered in the registry are the same .
Each use getService Method time , The registry will add 1, At the same time, it will record who is using the service . If you don't want to use the service , Log out of service .
bundleContext.ungetService(reference); listing = null;
6、 ... and 、OSGI The implementation of the
1、OSGI The concrete realization of
OSGI yes OSGi Alliance Made by the organization Java Modular specification , but OSGI The alliance did not give OSGI Implementation of container , The specific implementation is completed by the third-party manufacturer , At present, more OSGI The container has Apache Felix、Equinox、Spring DM.
2、OSGI Of JAVA Realization
A、Apache Felix
Apache Felix yes Apache One of our flags OSGi frame ,Felix It's a OSGi edition 4 canonical Apache Realization .Apache Felix The services provided cover almost all OSGi 4.2 Standards for , In addition, it also provides some non-standard functions , for example iPOJO.Apache Felix The frame itself is very compact , It only needs 3 One bag plus one shell Can run , Whether it's development or Debug It's very simple .
B、Equinox
Equinox yes Eclipse Flag OSGi frame , They are also Eclipse use , yes Eclipse Of PDE The bottom of the development environment .Equinox It's also quite a comprehensive framework , The functions provided are no better than Felix How much less .Equinox As development Eclipse Plugin More applications , If you want to develop a Web Program , You will feel that the functions and documents are not comprehensive .Equinox The biggest advantage lies in and Eclipse To combine closely , Once installed PDE, It already has Equinox, It's convenient in Eclipse Set and developed in Bundle, start-up 、 Deployment and other operations are also very simple , And there's a special Debug Interface .
C、Spring DM
Spring DM yes Spring Flag OSGi frame ,Spring DM The biggest feature of is the combination of Spring frame .
D、Knopflerfish
Knopflerfish yes OSGi The forerunner of , Is a fairly standard OSGi frame , Provides most standard functions .
3、OSGI Of C++ Realization
A、CTK Plugin Framework
CTK Is based on Qt Open source project developed to support biomedical image computing .
CTK Medium CTK Plugin Framework The module draws on OSGI Thought , And achieved almost complete OSGI frame API.
B、C++ Micro Services
C++ Micro Services Is based on OSGI Ideas for creating and managing modular software systems C++ library .
4、OSGI Of C Realization
Apache Celix Is based on C/C++ Of OSGI Specification implementation , Provides a way to use components and service-oriented programming (SOP) Develop a framework for modular applications .
Apache Celix The main use of C Language development , For support C++, Increased abstraction in the form of Libraries .
Official website :http://celix.apache.org/
7、 ... and 、OSGI Application example
We need to solve a few problems :
1. How to correctly understand and understand OSGI technology ?
Let's go back to some of our previous development scenarios , Suppose we use SSH(struts+spring+hibernate) Framework to develop our Web project , When we do product design and development, we are divided into modules , The purpose of our module division is to realize the communication between modules “ decoupling ”, The further purpose is to facilitate the control and management of a project .
After we modularize a project , We can hand over different modules to different developers to complete the development , Then the project manager put the completed modules together , Then assemble it into a final product . Generally, our development is based on this basic situation .
So what we expect when we develop is the function of the system , Divide the modules according to the functions of the system , in other words , The function of this product or the needs of customers is an important basis for division .
But we're in the development process , We have to keep in touch with each other , such as A The module should start from B The module gets some data , and B The module may call C Some methods in the module ( In addition to the common underlying tool classes ). So these modules are just a logical division .
The most important thing is , We will deploy the final project to tomcat perhaps jBoss To deploy in the server . So when we start the server , Can you close a module or function of the project ? It's obviously impossible , Once the server starts , All modules will start together , It takes up server resources , So you can't close the module , Suppose it can be forcibly removed , Will affect other functions .
The above are some limitations of our traditional modular development .
We have been pursuing a realm in software development , It's the real... Between modules “ decoupling ”、“ Separate ”, In this way, we will be more flexible in software management and development , Even when deploying projects to customers, it can be more flexible and controllable . But we used to use SSH We can't meet this requirement when we develop products with framework and other architecture patterns .
So we “ Architects ” Or top technical experts are trying to explore and try for modular development , And then our OSGI The new technical specifications came into being .
Now our OSGI Technology can meet what we said before : Complete separation in different modules , Not a logical separation , It's a physical separation , In other words, after running the deployment, you can directly remove some modules without stopping the server , The functions of other modules are not affected .
thus ,OSGI Technology will become very important in the future , Because it is on the way to decoupling modules , Walk faster than people often use now SSH The framework goes further . This technology will be widely used in the future 、 High access 、 Highly concurrent Java Modular development field , Or in the standardized management of the project , Will greatly exceed SSH The status of such a framework .
Now some mainstream application servers ,Oracle Of weblogic The server ,IBM Of WebSphere,JBoss, also Sun The company's glassfish The server , All the OSGI Provides strong support , It's all in OSGI Based on the technology of . There are so many large manufacturers supporting OSGI This technology , We can see OSGI The importance of Technology . So in the future OSGI Is a very important technology in the future .
however OSGI It is still inseparable from the support of the framework , because OSGI It also uses a lot of spring And other basic controls of the framework ( Because to achieve AOP Dependency injection and other functions ), But which project doesn't rely on a third party jar Well ?
2.OSGI How does technology help the development of our project ?
(1) Project presentation
Next, let's show it with the project code OSGI The charm of :
Let's not rush to understand how to use OSGI, Let's take a look at a project first OSGI The effect of .
( The following project code is an example in the online teaching video , I have no source code here )
( Say it in advance : The key point we need to learn is how to combine our shopping website OSGI technology , Make the project more flexible and controllable , The shopping website itself is not the key .)
First, in the Eclipse First open our single server version of the project :
Successful launch :
This is a Web project , Let's open the browser to see the effect :
It can be seen that it is an online shopping project .
Let's take a look at what we are based on OSGI What is the difference between technical projects and our general projects .
First, let's introduce the modules of this project :
1. Category display
https://img-blog.csdn.net/20160310173537333?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
2. Sub category display ( Sub products of major categories )
After clicking in, you will see the specific information of the product
3. The shopping cart
It's empty without shopping :
After buying :
4. Commodity management ( shelves 、 Off the shelf )
You can see , This project is no different from the projects we usually develop ( I know the interface is very simple = =), The key point is its startup and loading process .
(2) About servers
We use dynamic loading , That is to say “ Thermal deployment ” To start our project . That is to say , Our project puts it in Web After the container , We can take down some functions , And when it is taken down, it will not affect other modules .
We used to run tomcat When , Start the server , take Web The project is loaded at one time , A message like this will appear on the console :
https://img-blog.csdn.net/20160310173643287?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
But this is not the case when we started this project :
https://img-blog.csdn.net/20160310173703556?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
Then we are useless tomcat and jBoss, That's how to deploy and start Web What about the project ? It's impossible not to have Web Server middleware ? Here's what it tells you ,OSGI There is also an embedded technology Web Server's , Namely jetty.
We open this project Run Configuration Configuration window , Take a look at the plug-in package required to run this project :
You can see , Except for some Web The project needs jar package , Still have jetty The presence of the . So the server used is jetty, No more tomcat.
You may still be familiar with tomcat, about jetty Not too familiar with , So let's briefly introduce jetty:
jetty It is also an excellent Web Containers , It is better than tomcat Much more powerful ( Such as high concurrency , A long connection ). And its overall structure ratio tomcat Much lighter (tomcat More bloated ), You can go online to have a look at the specific differences .
(3) Running mode and plug-ins
Let's take a formal look at this project in OSGI Operation mode under :
When we started , Four modules are loaded , Namely :
According to the idea of modularization, they are four corresponding functional modules .
The engineering codes of their corresponding four function modules can be found in Eclipse see :
Let's take a look at our startup configuration ( Still open is Run Configuration Configuration window ):
The configuration is divided into “WorkSpace” and “Target Platform”, They are our workspace ( We write our own project modules and tool classes ) Plug in and running platform ( Some dependence jar Configuration of ) Plug in for , The combination of the two will start our project and it will run normally .
After we start the project , Enter instructions on the console “ss”, The operation of all our loaded plug-ins will appear :
https://img-blog.csdn.net/20160310173922491?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
When it starts up , It will load first Eclipse Of OSGI plug-in unit (Eclipse It's also a kind of OSGI The container of ):
We open our Eclipse The installation directory , And then find plugins Folder , You can see Eclipse All the plug-ins :
You can see that there are folders , Yes jar Form of plug-ins .
How do we understand plug-ins ?
Plug ins are actually developed tools or OSGI Container management and configuration jar package .
Let's open a folder type plug-in , You can see :
You can see inside except lib There are other things besides , And then there's a “OSGI-INF” Folder . Whatever it is , This is enough to explain our Eclipse It's just one. OSGI Containers .
(4) Hot deployment and hot start
Let's get back to the point , In the process of our startup , We don't stop running , Then stop one of the modules :
If we want to stop “ management ” modular :
That is to stop id by 22 Plug in for
result :
https://img-blog.csdn.net/20160310174029225?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
Then refresh our website homepage :
Found us “ management ” The module disappeared !
The disappearance of this module is not javascript Technology , It's a server technology , We uninstall it dynamically through the server .
After removing our management module , Other functions of the website will not be affected . So far, our server has not been suspended or shut down .
Let's stop again “ The shopping cart ” modular :
effect :
Other modules remain unaffected .
We closed two modules , Now the input ss Take a look at the operation of all plug-ins and modules :
You can see that our two modules are in RESOLVED state , That is, the pending state .
Of course, we can also deploy our module under the server open state :
If we start the shopping cart module :
https://img-blog.csdn.net/20160310174936589?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
Found the shopping cart back :
https://img-blog.csdn.net/20160310174946605?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
This is called hot deployment , That is, this project puts it in Web After the container , We can take down some functions , And when it is taken down, it will not affect other modules .
Let's have a real experience through the shopping website OSGI This technology has some powerful functions in project development and management .
————————————————
Copyright notice : This paper is about CSDN Blogger 「 Lotus leaf spring 」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
Link to the original text :https://blog.csdn.net/heyeqingquan/article/details/86491707
边栏推荐
- Listview is added and deleted at the index
- Django reports an error when connecting to the database. What is the reason
- Es module and commonjs learning notes -- ESM and CJS used in nodejs
- 用 Jmeter 工具做个小型压力测试
- 2022年上半年国家教师资格证考试
- Learning notes of "hands on learning in depth"
- AutoCAD - set layer
- Basic knowledge points
- Unity ugui source code graphic
- 【Leetcode】1352. Product of the last K numbers
猜你喜欢
LeetCode之单词搜索(回溯法求解)
Establish cloth effect in 10 seconds
Django reports an error when connecting to the database. What is the reason
Optimization scheme of win10 virtual machine cluster
Use of snippets in vscode (code template)
Panel panel of UI
小程序直播+电商,想做新零售电商就用它吧!
AutoCAD - set layer
UE fantasy engine, project structure
[paper notes] multi goal reinforcement learning: challenging robotics environments and request for research
随机推荐
【Leetcode】1352. Product of the last K numbers
AutoCAD - window zoom
Generate filled text and pictures
A complete attack chain
Lua GBK and UTF8 turn to each other
2022/7/1學習總結
Applet Live + e - commerce, si vous voulez être un nouveau e - commerce de détail, utilisez - le!
AutoCAD - Center zoom
3dsmax2018 common operations and some shortcut keys of editable polygons
AutoCAD - full screen display
win下一键生成当日的时间戳文件
Autocad-- dynamic zoom
Detailed explanation of the ranking of the best universities
Listview pull-down loading function
Redis has four methods for checking big keys, which are necessary for optimization
Listview is added and deleted at the index
Unity enables mobile phone vibration
Django reports an error when connecting to the database. What is the reason
2022 / 7 / 1 Résumé de l'étude
Es module and commonjs learning notes