An example of data cache application based on IBM Bluemix

Source: Internet
Author: User
Tags delete cache



Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka



Summary: Ibm®data cache for Bluemix is a cache service that supports distributed cache scenarios for WEB and mobile applications. The cache service uses data grid technology, where you can store key-value objects. Data Cache provides a business-ready, in-memory data grid (IMDG) that places data in a near-logical location and remains there as the business expands. It is easy to use and extend the performance and scalability of existing applications. It can help minimize redundant transactions, increase response time, and increase efficiency in your existing application infrastructure (supporting critical applications). For increased redundancy, the data cache provides a copy of the database stored in the cache. Therefore, the client application can still access the data in the cache in the event of a drop or outage.



Examples of this article visit: http://datacachetest.eu-gb.mybluemix.net/



bluxmix Account registration:https://apps.admin.ibmcloud.com/manage/trial/bluemix.html?cm_mmc=cmdevelopergcg-_- Bluemix-_-csdn-_-onlineeventq2


First, create the project and add the data cache service


1. Bluemix Personal Center Create engineering Web project



How to create a project to see the actual walkthrough of deploying a Java Web project based on the IBM Bluemix, when the project is created






2. Add Data Cache Service



The data cache service remotely leverages the caching capabilities of the DataGrid and allows you to perform create, retrieve, update, and delete operations.



You can go to the project and click Add Service or API, then search for data and find the data cache.






Choose a Basic Package:








Second, create a local Java Web project


The final project directory is as follows:






1. Create a Dynamic Web Project



2. Add Jar Package



Webcontent/web-inf/lib folder add Ogclient.jar, Json-org.jar



These two jar packages, ftp://public.dhe.ibm.com/cloud/bluemix/datacache/



3. Create the code that connects to the data cache



To use the data Cache service instance, you can find any data required by the application to communicate with the service instance in the VCAP_SERVICES environment variable. Your application needs to include the required variables to communicate with the Data Cache service. You can get variables Gridname, username, and password from the VCAP_SERVICES environment variable programmatically by including the following code snippet, and put the code in. This code fragment reads the VCAP_SERVICES environment variable:



The following code is not running on local eclipse, it has to be uploaded to the Bluemix project to run





public void Jspinit () {map<string, string> env = system.getenv ();//Get Bluemix current project String vcap=env.get ("Vcap_ SERVICES ");//Get environment variable String username=null; String Password=null; String Endpoint=null;         String Gridname=null;        Boolean foundservice=false;        if (vcap==null) {System.out.println ("No vcap_services found");                } else {try {jsonobject obj = new Jsonobject (VCAP);                String[] Names=jsonobject.getnames (obj); if (Names!=null) {for (String name:names) {if (Name.startswith ("Datacache")) {//Get Cache API J             Sonarray val = obj.getjsonarray (name);             Jsonobject serviceattr = val.getjsonobject (0);             Jsonobject credentials = Serviceattr.getjsonobject ("credentials");             Username = credentials.getstring ("username");                            Password = credentials.getstring ("password");             Endpoint=credentials.getstring ("Catalogendpoint"); GriDname= credentials.getstring ("Gridname");             System.out.println ("Found configured Username:" + username);             System.out.println ("Found configured password:" + password);             System.out.println ("Found configured endpoint:" + endpoint);             System.out.println ("Found configured Gridname:" + gridname);             Foundservice = true;             Break                                                                                                                                                               } }}} catch (Exception e) {}} if (!foundservice) {System.out.println ("did no T find WXS Service, using defaults "); } try {Objectgridmanager OGM = Objectgridmanagerfactory.getobjectgridmanager (); Clientsecurityconfiguration csc=null;csc=clientsecurityconfigurationfactory.getclientsecurityconfiguration (); Csc.setcredentialgenerator (New Userpasswordcredentialgenerator (Username,password)); Csc.setsecurityenabled (True) ; ClientclustercOntext CCC = Ogm.connect (endpoint, CSC, null); ObjectGrid Clientgrid = Ogm.getobjectgrid (CCC, gridname); ogsession = Client Grid.getsession (); } catch (Exception e) {System.out.println ("Failed to connect to grid!"); E.printstacktrace ();}}
In fact, the environment variables obtained in the interface are as follows








4. Create code to add, fetch, and delete caches






5. Merge Code





Because what we're going to do here is cache the data from the foreground, fetch the data, and so on. So the backstage is going to implement the data cache sent by the foreground. To do this, you can use the above code in combination. Create a new. jsp file as follows:



datacache.jsp





<%@ page pageencoding= "UTF-8"%><%@ page import= "java.util.Map"%><%@ page import= "Org.json.JSONArray"% ><%@ page import= "org.json.JSONException"%><%@ page import= "org.json.JSONObject"%><%@ page import= "com.ibm.websphere.objectgrid.*"%><%@ page import= "com.ibm.websphere.objectgrid.security.config.*"%> <%@ page import= "com.ibm.websphere.objectgrid.security.plugins.builtins.*"%><%! Session ogsession;public void Jspinit () {map<string, string> env = system.getenv ();//Get Bluemix current project String vcap=en V.get ("vcap_services");//Get environment variable String username=null; String Password=null; String Endpoint=null;         String Gridname=null;        Boolean foundservice=false;        if (vcap==null) {System.out.println ("No vcap_services found");                } else {try {jsonobject obj = new Jsonobject (VCAP);                String[] Names=jsonobject.getnames (obj);           if (Names!=null) {for (String name:names) {         if (Name.startswith ("Datacache")) {//Get Cache API Jsonarray val = obj.getjsonarray (name);             Jsonobject serviceattr = val.getjsonobject (0);             Jsonobject credentials = Serviceattr.getjsonobject ("credentials");             Username = credentials.getstring ("username");                            Password = credentials.getstring ("password");             Endpoint=credentials.getstring ("Catalogendpoint");             Gridname= credentials.getstring ("Gridname");             System.out.println ("Found configured Username:" + username);             System.out.println ("Found configured password:" + password);             System.out.println ("Found configured endpoint:" + endpoint);             System.out.println ("Found configured Gridname:" + gridname);             Foundservice = true;             Break                                                                                                                                               }                }}} catch (Exception e) {}} if (!foundservice) {System.out.println ("Do not do not find WXS service, US ing defaults "); } try {Objectgridmanager OGM = Objectgridmanagerfactory.getobjectgridmanager (); Clientsecurityconfiguration csc=null;csc=clientsecurityconfigurationfactory.getclientsecurityconfiguration (); Csc.setcredentialgenerator (New Userpasswordcredentialgenerator (Username,password)); Csc.setsecurityenabled (True) ; Clientclustercontext CCC = Ogm.connect (endpoint, CSC, null); ObjectGrid Clientgrid = Ogm.getobjectgrid (CCC, gridname); o Gsession = Clientgrid.getsession (); } catch (Exception e) {System.out.println ("Failed to connect to grid!"); E.printstacktrace ();}} %><%try {request.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/plain");   Response.setcharacterencoding ("UTF-8"); Objectmap is used to store cached content Objectmap map=ogsession.getmap ("Sample. NONE.    P "); String key = Request.getparameter ("key"); String operation=request.getparameter ("operation"); Object RetriEvedvalue;if ("Get". Equals (operation)) {//Get cached content Retrievedvalue=map.get (key); Response.getwriter (). Write (Retrievedvalue==null? " Null ": Retrievedvalue.tostring ());  } else if ("Put". Equals (operation)) {//Store cache contents String NewValue = Request.getparameter ("value");  Map.upsert (Key,newvalue);//You can implement update or insert Response.getwriter () on map. Write ("[PUT]");    } else if ("delete". Equals (operation)) {//delete cache Map.Remove (key);  Response.getwriter (). Write ("[DELETED]");  }} catch (Exception e) {System.out.println ("Failed to perform operation on map"); E.printstacktrace ();}%>

6, write the foreground page code





Here the front desk uses AJAX request (do not know Ajax can see here Ajax example explain and technical principle) to datacache.jsp file to cache data, fetch data, delete data. The entire code is as follows:



Index.html





<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

7. Launch Tomcat locally to run a bit
	







Confirm that the page shows no problem here you how to enter data, click will definitely have a problem, because has not been deployed to Bluxmix: The following error: three, packaging and publishing to Bluemix1. Pack the local war package. Use directly in eclipse Then select the directory: Look at the final result: Note: You can also use the project directory under the console, and then enter
Package the current directory into a war package jar CVF Datacachetest.war */.
However, this method finally packaged the war package I uploaded after the launch failed. It is therefore not recommended to use this method.

2. Upload the war package to your personal Bluemix center
(1), Login
CF Login enter user name, password, select workspace or direct CF login-u [email protected]-o [email protected]-S workspace name
Remember to change your email address to your own.

(2), Upload War package
CF Push Datacachetest-p D:\DataCacheTest.war-m 512M Remember to specify a space size of 512M

Finally, if it shows the following:
Indicates successful upload and successful operation
Iv. Verification Effect
Input URL: http://datacachetest.eu-gb.mybluemix.net/input, click Storage cache Content
Note that the last shown below indicates that the cache storage is successful, just wait a bit (the server, after all, in the United States, the speed of return will be slower), display put to indicate success!
Of course, you can also look at the logs: for example, the storage cache above
Here's what the log looks:
There is the cache: Enter the key on the page, and then click the button to take the cache
Delete cache: Enter key on the page and click the Delete Cache button


v. Monitoring IBM Data Cache for BluemixBelow are the tools provided by Bluxmix to monitor the data cache

After you connect your application to Data cache, you can monitor the cache usage of your WEB application. Click the service instance of the IBM Bluemix Dashboard to display the chart for your application. Note that this content will not be displayed until the service is bound and the program is started!

Used Space
This chart contains a view of the total cache capacity based on the IBM service plan. The total capacity displayed includes 1 copies of the data stored in the data grid. You can always increase the limit by purchasing more capacity for your application.
Throughput
This chart is a snapshot view of throughput within 5 minutes. You can expand this chart to a larger view, showing 1 hours of throughput.
Transaction time
This chart is a snapshot view of the transaction time within 5 minutes, measured in transactions per millisecond. You can expand this chart to a larger view, showing 1 hours of transaction time.
Shooting
This chart is a snapshot view of the cache hit ratio. You can expand this chart to a larger view, showing a 1-hour hit rate.


Vi. Problems encounteredProblems encountered: The first time the project was uploaded to the deployment. When trying to access the deployed application, open the URL, I have the following message:404 Not found:requested route (' guesstheword.mybluemix.net ') does not exist.
This seems to be wrong. There is obviously a problem somewhere, and the problem seems to be related to the application running on Bluemix, because the application works locally. WORKAROUND: Delete the project on Bluxmix and re-add the service. Then repackage the local war package (preferably through Eclipse's Expot method). Finally, re-upload it!
Examples of this article visit: http://datacachetest.eu-gb.mybluemix.net/





An example of data cache application based on IBM Bluemix


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.