基于IBM Bluemix的数据缓存应用实例

Posted Evankaka

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于IBM Bluemix的数据缓存应用实例相关的知识,希望对你有一定的参考价值。

         林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka

          摘要:IBM® Data Cache for Bluemix 是高速缓存服务,支持 Web 和移动应用程序的分布式高速缓存场景。高速缓存服务使用数据网格 技术,您可以在其中存储键值对象。Data Cache 提供了一个业务就绪的内存数据网格 (IMDG),其将数据放在接近逻辑的位置并随着业务扩展仍将其保留在此。很容易使用并扩展现有应用程序的性能和可伸缩性。它可以帮助将冗余事务降到最低、提高响应时间并增加现有应用程序基础结构(支持重要应用程序)中的效率。对于增加的冗余,Data Cache 提供高速缓存中存储的数据副本。因此,万一掉线或停运,客户机应用程序仍可访问高速缓存中的数据。

本文实例访问:http://datacachetest.eu-gb.mybluemix.net/

BluxMix账号注册:https://apps.admin.ibmcloud.com/manage/trial/bluemix.html?cm_mmc=CMDeveloperGCG-_-Bluemix-_-CSDN-_-onlineeventQ2

一、创建工程并添加Data Cache服务

1、Bluemix个人中心创建工程web工程

如何创建工程可看基于IBM Bluemix部署Java Web项目实战演练,这时创建后的工程


2、添加Data Cache 服务

Data Cache 服务在远程利用数据网格的高速缓存功能并使您可以执行创建、检索、更新和删除操作。

可以进入到项目中,然后点击添加服务或API,然后搜索data,找到Data Cache即可。


选择基本的套餐:



二、创建本地Java web工程

最后整个工程目录如下:


1、创建一个Dynamic web Project

2、添加jar包

 WebContent/WEB-INF/lib 文件夹添加ogclient.jar 、json-org.jar 

这两个jar包下载地址,ftp://public.dhe.ibm.com/cloud/bluemix/datacache/

3、创建连接Data cache的代码

要使用 Data Cache 服务实例,可在 VCAP_SERVICES 环境变量中找到应用程序与服务实例进行通信所需的任何数据。您的应用程序需要包含所需的变量,以与 Data Cache 服务进行通信。您能通过包括以下代码片段,以编程方式从 VCAP_SERVICES 环境变量获取变量 gridName、username 和 password,并放入代码。此代码片段将读取 VCAP_SERVICES 环境变量:

下面的代码放在本地eclipse是无法运行的,它得上传到Bluemix工程中才可以运行

public void jspInit() {
 		Map<String, String> env = System.getenv();//取得bluemix的当前工程
 		String vcap=env.get("VCAP_SERVICES");//取得环境变量 
 		
 		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")) { //取得缓存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("Did not 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 = clientGrid.getSession();
			
 		} catch(Exception e) {
 			System.out.println("Failed to connect to grid!");
 			e.printStackTrace();
 		}
}
其实取得的环境变量在界面上如下


4、创建增、取、删除缓存的代码

ObjectMap map=ogSession.getMap("mymap.NONE.P");
map.upsert("key1", "value1");
Object value = map.get("key1");
map.remove("key1"); 
5、合并代码

因为这里我们要实现的是从前台缓存数据,取数据等。所以后台就要实现将前台传过来的数据缓存。为此,可以将上面的代码合并使用。新建一个.jsp文件如下:

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();//取得bluemix的当前工程
 		String vcap=env.get("VCAP_SERVICES");//取得环境变量 
 		
 		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")) { //取得缓存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("Did not 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 = 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用来存储缓存内容 
			ObjectMap map=ogSession.getMap("sample.NONE.P");
			
		    String key = request.getParameter("key");			
			String operation=request.getParameter("operation");
			Object retrievedValue;
			if("get".equals(operation)) { 	//取得缓存内容
			  retrievedValue=map.get(key);
			  response.getWriter().write(retrievedValue==null?"null":retrievedValue.toString());
			 
			} else if("put".equals(operation)) { //存储缓存内容
			  String newValue = request.getParameter("value");
			  map.upsert(key,newValue);//可以对map实现update or insert  
			  response.getWriter().write("[PUT]");
			  
			} else if("delete".equals(operation)) { //删除缓存 
			  map.remove(key);			  
			  response.getWriter().write("[DELETED]");			  
			}
			
		} catch(Exception e) {
			System.out.println("Failed to perform operation on map");
			e.printStackTrace();
		}
 %>
 

6、编写前台页面代码

这里前台使用ajax请求(不懂ajax可看这里Ajax实例讲解与技术原理)到dataCache.jsp文件去缓存数据、取数据、删除数据。整个代码如下:

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>IBM Bluemix缓存实例</title>
<body  οnlοad="load()">
<script language="javascript" type="text/javascript">
function load(){	
  document.getElementById('get').addEventListener("click", getClicked, false);
  document.getElementById('put').addEventListener("click", putClicked, false);
  document.getElementById('delete').addEventListener("click", deleteClicked, false);
}
//发送请求
function sendRequest(operation) {
	var ajaxRequest;  
	var key = encodeURIComponent(document.getElementById('key').value);
	var value = encodeURIComponent(document.getElementById('value').value);
	
	ajaxRequest = new XMLHttpRequest();
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			var result = ajaxRequest.responseText;
			document.getElementById('value').value=result;
        }
	}
	//发送ajax的get请求 
	ajaxRequest.open("GET", "dataCache.jsp?operation="+operation+"&key="+key+"&value="+value, true);
	ajaxRequest.send(null); 
}
//取得缓存
function getClicked() {
  sendRequest('get');
}
//存储缓存
function putClicked() {
  sendRequest('put');
}
//删除缓存
function deleteClicked() {  
  sendRequest('delete');
}
</script>
    <h3>IBM Bluemix缓存实例:</h3> 
	Key:   <input id="key" type='text' name='key' /> <br>
	Value:  <input id='value' type="text" name='value' /><br><br>
	<button id='get'>根据KEY取缓存内容</button>
	<button id='put'>存储缓存内容</button>
	<button id='delete'>根据KEY删除缓存内容</button><br>
	
</body>
</html>

7、本地启动tomcat运行一下