JBoss series twenty-one: JBossCache core API

brief introduction

The department introduced JBossCache related mainly API, we aim through this part of the description, the reader can use JBossCache API, JBossCache use in their own applications.

Cache Interface

Cache interface is the primary mechanism for interaction and JBossCache. It was constructed using CacheFactory and optionally activated. CacheFactory allows you to create from the Cache Configuration object or an XML file. Organizing the data cache to the tree structure consisting of nodes in the. Once you have a reference to a Cache, you can use it to look up Node objects in a tree structure where, and store data.


Note that the chart above only describes some of the popular API methods. Read the above interface API Javadoc is to learn the best way to armor.

Initialize and start caching

Examples of the Cache interface can only be created by CacheFactory. This is different JBoss Cache 1.x, the old TreeCache direct initialization. CacheFactory provides a number of overloaded methods for creating a Cache, but they are basically doing the same thing:

  • Gain access to Configuration, or passed as a method parameter or by parsing XML content and constructing. XML content can come from the input stream, classpath or file system location. For more information about Configuration then there will be described in detail.
  • Cache initialization and provide a reference to the Configuration
  • Alternatively invoke a cache create () and start () method
The following example code segment is created using the default configuration values ​​and start caching the most simple mechanism:

CacheFactory factory = new DefaultCacheFactory();
Cache cache = factory.createCache();

In the following code snippet, we tell CacheFactory to find and parse the configuration file on the classpath:

CacheFactory factory = new DefaultCacheFactory();
Cache cache = factory.createCache("cache-configuration.xml");

In the following code snippet, we configure the cache by file, but want to modify the configuration elements by the program. So we do not notice factory to start the cache, but their own to start:

CacheFactory factory = new DefaultCacheFactory();
Cache cache = factory.createCache("/opt/configurations/cache-configuration.xml",false);
Configuration config = cache.getConfiguration();
config.setClusterName(this.getClusterName());
// Have to create and start cache before using it
cache.create();
cache.start();

Cache and retrieve data

As above, we initialize and start the cache, let's use the Cache API to access the cache of Node and then do some simple read and write to this node, the following code snippet:

28     Cache cache = createCacheUseDefault();
 29     Node rootNode = cache.getRoot();
 30     Fqn helloWorldFqn = Fqn.fromString("/root/helloWorld");
 31     Node helloWorld = rootNode.addChild(helloWorldFqn);
 32     helloWorld.put("isJBossCache", Boolean.TRUE);
 33     helloWorld.put("content", new Content("HelloWorld"));
 35     System.out.println(helloWorld.get("isJBossCache"));
 36     System.out.println(helloWorld.get("content"));
 37     System.out.println(helloWorld.getFqn());
 38     System.out.println(helloWorld.getKeys());
 40     helloWorld.remove("isJBossCache");
 41     helloWorld.remove("content");
43     System.out.println(helloWorld.get("isJBossCache"));
 44     System.out.println(helloWorld.get("content"));
46     rootNode.removeChild(helloWorldFqn);

After creating the line 28-29 as a default node with a Cach acquired; 30 JBoss Cache line structure data stored in a tree, the tree structure comprising a plurality of nodes, all nodes are used to identify Fqn; create a new node line 31-33 , and the data storage node; read data stored in the test line 35-38; 40-41 rows of data to remove added; 46 is about to be removed from the newly created node with the node.

For ease of use, Cache interface is also open to "The Fqn category" as a parameter performed put / get / remove operations:

Cache cache = createCacheUseDefault();
Node rootNode = cache.getRoot();
Fqn helloWorldFqn = Fqn.fromString("/root/helloWorld");
Node helloWorld = rootNode.addChild(helloWorldFqn);

cache.put(helloWorldFqn, "isJBossCache", Boolean.TRUE);
cache.put(helloWorldFqn, "content", new Content("HelloWorld"));

System.out.println(helloWorld.get("isJBossCache"));
System.out.println(helloWorld.get("content"));
System.out.println(cache.getRoot().hasChild(helloWorldFqn));

cache.removeNode(helloWorldFqn);

And organizing the data using the node structure

It should be seen as a node named logical data groups. Node should be used to contain the data in a single data record, e.g., a person or account information. It should have all the aspects of the cache - locking, cache loading, replication and eviction - for each node settings. Thus, a single node in the stored information in any packet will be treated as a single atomic unit.

Fqn class

Fqn previous section used in the examples in class; now let us be more understanding. Fully Qualified Name (Fqn) represents the name list corresponding to the package buffer mechanism tree in the path to a location. The list of elements is usually String but can be any Object or mixed type. Fqn representative of a particular node to a path or a path of the Cache.

This path can be absolute (ie, relative to the root node), also with respect to any node in the cache. Fqn document on the use of API calls in the API will tell you whether relative or absolute Fqn. Fqn provides a large number of factory method, please refer to JBossCache Javadoc. The following examples illustrate the most common way to create FQN:
15    Fqn strFqn = Fqn.fromString("/people/Smith/Joe/");
16    Fqn eleDqn = Fqn.fromElements("accounts", "NY", new Integer(12345));

As we create a line 15 Fqn Joe point node, the node Joe Smith at a parent node, and the node A node people under Smith, we created by Fqn String String; 16 line with other data types we create Fqn. Special attention, Fqn.fromElements ( "a", "b", "c") and Fqn.fromString ( "/ a / b / c") equivalent, which are created pointing to a node c Fqn.

Stop and destroy caches

Stop and destroy the cache after use is common practice, particularly where a large number of JGroups channel using cache in a cluster application, stop and destroy caches can ensure a proper clean-up network sockets and maintenance threads and other resources. We can stop by the methods provided cache and destroy the cache, as follows:

cache.stop();
cache.destroy();

Note has been called stop () cache can start () to restart the start. Similarly, it has called destroy () cache can also be () re-created with create, and call start () to restart the start cache.

Cache Mode

Although strictly speaking, not part of the API cache mode, but the mode of operation of the cache may affect the behavior of any put or remove operation, so here we will simply describe these patterns. JBoss Cache mode is defined by org.jboss.cache.config.Configuration.CacheMode, which is an enumerated type, including the cache mode as follows:

  • LOCAL - local, non-clustered cache mode. Local caches do not join a cluster and not the other nodes in the cluster communication
  • REPL_SYNC - synchronous mode. Modify other cache cluster cache copy. Synchronous replication means that modifications are replicated and the caller blocks until replication acknowledgments are received.
  • REPL_ASYNC - asynchronous mode. And above REPL_SYNC similar to other caches in the cluster to modify the cache copy. But the caller does not block until replication acknowledgments are received
  • INVALIDATION_SYNC - non-validating synchronous mode. If the cache is configured for invalidation rather than replication, each time the data is modified, the other caches in the cluster receive a message informing them of this data is now stale and should be evicted from the cache. This reduces the replication load, but also can make the remote cache of stale data
  • INVALIDATION_ASYNC - non-validating asynchronous mode. And above, except this failure mode can result in failure of the asynchronous broadcast information

Adding a Cache Listener - registering for cache events

JBoss Cache provides a convenient mechanism to register an event notification cache:

Object myListener = new MyCacheListener();
cache.addCacheListener(myListener);

Annotation methods need to be public and has a void return type, or a type org.jboss.cache.notifications.event.Event had accepted as the only parameter subtype. We can add an event in the cache include:

  •  @ CacheStarted- annotation method to receive notifications when you start in the cache. These methods need to accept a parameter type belongs in CacheStartedEvent
  • @ CacheStopped- annotation method to stop receiving notifications in the cache. These methods need to accept a parameter type belongs in CacheStoppedEvent
  • @ NodeCreated- annotation method to receive notification when a node is created. These methods need to accept a parameter type belongs in NodeCreatedEvent
  • @ NodeRemoved- annotation method to receive notifications when you delete a node. These methods need to accept a parameter type belongs in NodeRemovedEvent
  • @ NodeModified- annotation methods to receive notification when modifying the node. These methods need to accept a parameter type belongs in NodeModifiedEvent
  • @ NodeMoved- annotation methods to receive a notification when the mobile node. These methods need to accept a parameter type belongs in NodeMovedEvent
  • @ NodeVisited- annotation method to receive notifications when the access point. These methods need to accept a parameter type belongs in NodeVisitedEvent
  • @ NodeLoaded- annotation method to receive notification when a node is loaded from CacheLoader years. These methods need to accept a parameter type belongs in NodeLoadedEvent
  • @ NodeEvicted- annotation method to receive notifications when the node is evicted from memory. These methods need to accept a parameter type belongs in NodeEvictedEvent
  • @ NodeInvalidated- annotation method to receive notification when a remote node failure event due evicted from memory. These methods need to accept a parameter type belongs in NodeInvalidatedEvent
  • @ NodeActivated- annotation method to receive notifications when a node is activated. These methods need to accept a parameter type belongs in NodeActivatedEvent
  • @ NodePassivated- annotation method to receive notifications when a node is passivated. These methods need to accept a parameter type belongs in NodePassivatedEvent
  • @ TransactionRegistered- annotation method to receive notification when the cache registration javax.transaction.Synchronization has been registered in the transaction manager. These methods need to accept a parameter type belongs in TransactionRegisteredEvent
  • @TransactionCompleted - annotation method receives notification to receive a commit or rollback call from a cache in a registered transaction manager. These methods need to accept a parameter type belongs in TransactionCompletedEvent
  • @ ViewChanged- annotation method for receiving notification when the change in the group structure of the cluster. These methods need to accept a parameter type belongs in ViewChangedEvent
  • @ CacheBlocked- annotation method to receive notification when blocked because state transition event in the cache operation. These methods need to accept a parameter type belongs in CacheBlockedEvent
  • @ CacheUnblocked- annotation method to receive notification when the state transition event is canceled because of obstruction in the cache operation. These methods need to accept a parameter type belongs in CacheUnblockedEvent
  • @ BuddyGroupChanged- annotation methods to receive a notification when a cluster node or abandoned due Buddy updated, more recent addition of Buddy Buddy modify its group. These methods need to accept a parameter type belongs in BuddyGroupChangedEvent    

We give below a cache registration event example:

14 @CacheListener
15 public class MyListener {
17         @CacheStarted
18         @CacheStopped
19         public void cacheStartStopEvent(Event e) {
20                 switch (e.getType()) {
21                 case CACHE_STARTED:
22                         System.out.println("Cache has started");
23                         break;
24                 case CACHE_STOPPED:
25                         System.out.println("Cache has stopped");
26                         break;
27                 }
28         }
30         @NodeCreated
31         @NodeRemoved
32         @NodeVisited
33         @NodeModified
34         @NodeMoved
35         public void logNodeEvent(NodeEvent e) {
36                 System.out.println(e.getType() + " on node " + e.getFqn() + " has occured");
37         }

cacheStartStopEvent () method is transported as 17-18 when to start or stop a cache line, print out an error message and according to the type of event; the first 30-34 rows node is created, removed, access, mobile is logNodeEvent () method is transporting, detailed event type is printed out. We tested MyListener end with the following code:

13     CacheFactory factory = new DefaultCacheFactory();
14     Cache cache = factory.createCache(false);
15     MyListener myListener = new MyListener();
16     cache.addCacheListener(myListener);
17     cache.start();
19     Node root = cache.getRoot();
20     Fqn abcFqn = Fqn.fromString("/a/b/c");
21     Node abc = root.addChild(abcFqn);
22     abc.put("content", new Content("abc test"));
23     abc.get("content");
24     cache.removeNode(abcFqn);
25     cache.stop();
26      cache.destroy();

As lines 13-14 using DefaultCacheFactory create a Cache; 15-16 cache line registration event; 17 row start Cache; creation abc nodes, lines 19-23, and add the node check fetch, delete data; 24-26 lines removed node, closed Cache, run the code output terminal as follows:

Cache has started
NODE_CREATED on node /a has occured
NODE_CREATED on node /a has occured
NODE_CREATED on node /a/b has occured
NODE_CREATED on node /a/b has occured
NODE_CREATED on node /a/b/c has occured
NODE_CREATED on node /a/b/c has occured
NODE_MODIFIED on node /a/b/c has occured
NODE_MODIFIED on node /a/b/c has occured
NODE_MODIFIED on node /a/b/c has occured
NODE_MODIFIED on node /a/b/c has occured
NODE_VISITED on node /a/b/c has occured
NODE_VISITED on node /a/b/c has occured
NODE_REMOVED on node /a/b/c has occured
NODE_REMOVED on node /a/b/c has occured
Cache has stopped

Synchronous and Asynchronous Notification

By default, all notifications are synchronized so that they occur in the caller's thread generated event. Ensure cache listener to be running will not take long to realize the task thread is a good idea. Or, you can set CacheListener.sync property is false, then you will not be notified in the caller's thread.

Cache loader

Cache loaders are an important part of JBoss Cache. They allow persistence of nodes to disk or to remote cache cluster, and allows passivation when caches run out of memory. In addition, the implementation of cache loader allows JBossCache "warm starts", at this time the memory state can be preloaded from persistent storage. JBossCache comes to realize a lot of cache loader. JBossCache cache loader listed below provided:

  • org.jboss.cache.loader.FileCacheLoader- is a basic, based on the file system cache loader that persists data to disk. It is non-transactional, and the performance in general, but it does a very simple program. It is mainly used for testing, it is not recommended to be used in a production environment
  • It uses the JDBC connection org.jboss.cache.loader.JDBCCacheLoader- storage state. Connection from an internal pool (use c3p0 pooling library) or configured in a data source created and maintained. This cache loader connected database can be local or may be remote
  • org.jboss.cache.loader.BdbjeCacheLoader- It uses Oracle's BerkeleyDB-based transactional database to persist data files. It is transactional, and the performance is very good but may have limited license
  • org.jboss.cache.loader.JdbmCacheLoader- BerkeleyDB open source alternatives
  • org.jboss.cache.loader.tcp.TcpCacheLoader- by "one kind" far cache "pattern" use TCP socket to "persist" data to a remote cluster
  • org.jboss.cache.loader.ClusteredCacheLoader- used as a "read-only" cache loader, then the other nodes in the cluster by status inquiry. When the cost of a full state transfer is too high, it is preferred, in which case the state is lazy loaded   

Use eviction policy (Eviction Policy)

Eviction policy cache loader is counterparts. To ensure that the cache memory does not run out when filling, use eviction policy is necessary. Eviction algorithm running in a separate thread expelled memory state and frees memory. If equipped with a cache loader, the state can be obtained from the cache loader when needed. Eviction policy can be configured for each zone, so different subtrees in the cache could have different eviction preferences. JBossCache registration comes with several strategies:

  •  org.jboss.cache.eviction.LRUPolicy- expelled least recently used nodes when reaching the limit
  • org.jboss.cache.eviction.LFUPolicy- expelled from the least frequently used nodes when reaching the limit
  • org.jboss.cache.eviction.MRUPolicy- expelled most recently used nodes when it reaches the limit
  • org.jboss.cache.eviction.FIFOPolicy- when reaching the limit in accordance with the order of eviction FIFO node
  • org.jboss.cache.eviction.ExpirationPolicy- evicted node-based expiry time each node is configured policy
  • org.jboss.cache.eviction.ElementSizePolicy - The key held by the node / nodes value selection number eviction policy





Reproduced in: https: //my.oschina.net/iwuyang/blog/197197

Guess you like

Origin blog.csdn.net/weixin_34085658/article/details/91897332