java开发之阿里云对象存储OSS和云数据库Memcache的使用
web开发中标配:aliyun ECS(阿里云服务器),aliyun RDS(阿里云数据库),aliyun OSS(阿里云对象存储),aliyun Memcache(阿里云缓存数据库)。
今天就介绍下OSS和Memcache的使用方法(开通方法就不详细介绍了)。
1 OSS使用demo
首先导入oss开发包
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.0.6</version> </dependency>
导入开发包后开发代码如下:
package com.cyparty.security.utils; import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.ObjectMetadata; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; /** * Created by Shadow on 2016/4/28. */ public class OssUtil { public static void main(String[] args) { getOSSUrl("E:/1.jpg"); } public static String getOSSUrl(String filepath){ try { File file = new File(filepath); String file_name=filepath.split("/")[filepath.split("/").length-1]; String OssUrl=null; if (file.exists() && file.length() > 0) { OssUrl= OssUtil.getOssFilePath(file_name, filepath); } return OssUrl; }catch (Exception e){ e.printStackTrace(); return null; } } /** * 获取上传到OSS的图片连接 * * @param fileName 完整的文件名 * @param uploadFilePath 文件的路径 * @return 来自OSS的Url地址 */ private static String getOssFilePath(String fileName, String uploadFilePath) { String uri = ""; // 创建OSSClient对象 //todo:注意查看要链接的bucket服务器位置(shanghai or beijing or hangzhou) String bucket_name="laihui"; String bucket_source="oss-cn-shanghai.aliyuncs.com"; String accessKeyId="XXXXXXXX"; String secretAccessKey="XXXXXXXXXXXXXX"; OSSClient client = new OSSClient(bucket_source, accessKeyId, secretAccessKey); //上传图片 String key="security/images/"+Utils.getCurrenTimeStamp()/1000+"-"+fileName; //指定文件上传到bucket下面的那个文件夹下及文件名 boolean isSuccess= uploadFile(client, bucket_name, key, uploadFilePath);//指定bucket if (isSuccess) { //uri = "laihui.oss-cn-shanghai.aliyuncs.com/" + key; uri = bucket_name+bucket_source +"/"+ key; } return uri; } /** * 将本地图片上传至OSS的方法 * * @param client OSS外网域名 * @param bucketName bucket的名字 * @param key 图片的名字 * @param filePath 所上传图片的路径 * @return boolean类型的成功与失败状态 */ private static boolean uploadFile(OSSClient client, String bucketName, String key, String filePath) { int MAX_TRY = 3; int downloadTurn = 0; boolean uploadSuccess = false; while (downloadTurn < MAX_TRY) { try { File file = new File(filePath); if ((!file.exists()) || file.length() == 0) { uploadSuccess = false; break; } ObjectMetadata objectMeta = new ObjectMetadata(); objectMeta.setContentLength(file.length()); // 可以在metadata中标记文件类型 if (!client.doesObjectExist(bucketName, key)) { //System.out.println("开始上传文件" + filePath); InputStream input = new FileInputStream(file); client.putObject(bucketName, key, input, objectMeta); System.out.println(filePath+"上传成功!"); uploadSuccess = true; break; } else { uploadSuccess = true; break; } } catch (Exception e) { e.printStackTrace(); } } return uploadSuccess; } }
accessKeyId和secretAccessKey查看方法如下图,选中个人账号-->点击-->accessKeys-->查看
2 Memcache的使用
首先导入开发包-->下载地址,导入项目中后,具体代码如下
package com.cyparty.laihui.utilities; import com.alibaba.fastjson.JSONObject; import net.spy.memcached.AddrUtil; import net.spy.memcached.BinaryConnectionFactory; import net.spy.memcached.MemcachedClient; import net.spy.memcached.internal.OperationFuture; public class Memcache { private static MemcachedClient cache=null; public static MemcachedClient getCache() { final String host = "XXXXXXX.m.XXXXXXX.ocs.aliyuncs.com"; //控制台上的“内网地址” final String port = "11211"; //默认端口 11211,不用改 if(cache==null) { try { cache = new MemcachedClient(new BinaryConnectionFactory(), AddrUtil.getAddresses(host + ":" + port)); } catch (Exception e) { cache=null; System.out.println("getCache Error:"+e.getMessage()); } } return cache; } public static JSONObject getMemcache(String where){ JSONObject result=new JSONObject(); try { MemcachedClient cacheClient=getCache(); if (cacheClient.get(where)==null){ result.put("cache_status","0"); return result; }else { return (JSONObject)cacheClient.get(where); } } catch (Exception e) { e.printStackTrace(); } result.put("status","0"); return result; } public static void setMemcache(String where,JSONObject resultObject) { MemcachedClient cacheClient = null; try { cacheClient = getCache(); //向OCS中存一个key为"ocs"的数据,便于后面验证读取数据 String key = where; JSONObject value =resultObject; int expireTime = 60*60*24*10; // 过期时间10day,单位s; 从写入时刻开始计时,超过expireTime s后,该数据过期失效,无法再读出; OperationFuture future = cacheClient.set(key, expireTime, value); System.out.println("Set操作完成key为"+key); future.get(); // 确保之前(mc.set())操作已经结束 //执行get操作,从缓存中读数据,读取key为"ocs"的数据 System.out.println("Get操作:" + cache.get(key)); } catch (Exception e) { e.printStackTrace(); } } public static void setMemcache(String token,int id,int expireTime) { MemcachedClient cacheClient = null; try { cacheClient = getCache(); //向OCS中存一个key为"ocs"的数据,便于后面验证读取数据 String key = token; int value =id; if(expireTime<=0) { expireTime = 60 * 60 * 2; // 过期时间,单位s; 从写入时刻开始计时,超过expireTime s后,该数据过期失效,无法再读出; } OperationFuture future = cacheClient.set(key, expireTime, value); System.out.println("Set操作完成!链接为"+key); future.get(); // 确保之前(mc.set())操作已经结束 //执行get操作,从缓存中读数据,读取key为"ocs"的数据 System.out.println("Get操作:" + cache.get(key)); } catch (Exception e) { e.printStackTrace(); } } }