java缓存(MemChachedClient)
程序员文章站
2024-01-09 13:54:28
...
1 下载memcached-1.2.1-win32.zip 并且解压.
2 新建web project项目 名字自己取,然后导入必要的包,alisoft-xplatform-asf-cache-2.5.1.jar,commons-logging-1.0.3.jar,log4j-1.2.13.jar
3 新建类 user.java
package bean;
import java.io.Serializable;
public class User implements Serializable{
/**
* 序列号
*/
private static final long serialVersionUID = -3896605600471191953L;
private int uid;
private String uname;
private String upass;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
}
4 新建 JdbcConnector.java
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcConnector {
// 定义数据库连接常量
private final static String DRIVER = "com.mysql.jdbc.Driver";
private final static String URL = "jdbc:mysql://192.168.1.13:3306/test";
private final static String DBNAME = "root";
private final static String DBPASS = "123456";
/**
* 得到数据库连接
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public Connection getConn()throws ClassNotFoundException,SQLException {
// 加载驱动
Class.forName(DRIVER);
// 通过DriverManager对象得到连接
Connection conn = DriverManager.getConnection(URL,DBNAME,DBPASS);
// 返回数据库连接
return conn;
}
}
5 新建 UserDao.java
package util;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import bean.User;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
public class UserDao extends JdbcConnector {
// 定义全局变量
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
/**
* 根据Id查询用户
* @param uid
* @return
*/
public User getUserById(int uid) {
// 创建User对象
User user = null;
// 创建SQL语句
String sql = "select * from user where uid=?";
try {
// 获得数据库连接
conn = (Connection) this.getConn();
// 通过Connection对象创建PrepareStatement对象
pstmt = (PreparedStatement) conn.prepareStatement(sql);
// 设置SQL语句的参数
pstmt.setInt(2, uid);
// 执行查询,将查询结果赋给ResultSet对象
rs = (ResultSet) pstmt.executeQuery();
// 遍历指针
while (rs.next())
{
user = new User();
user.setUid(rs.getInt("uid"));
user.setUname(rs.getString("uname"));
user.setUpass(rs.getString("upass"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
/**
* 查询所有用户
* @return
*/
@SuppressWarnings("unchecked")
public List getUserList() {
// 创建ArrayList对象
List userList = new ArrayList();
// 创建SQL对象
String sql = "select * from user";
try {
conn = (Connection) this.getConn();
pstmt = (PreparedStatement) conn.prepareStatement(sql);
rs = (ResultSet) pstmt.executeQuery();
while (rs.next())
{
User user = new User();
user.setUid(rs.getInt("uid"));
user.setUname(rs.getString("uname"));
user.setUpass(rs.getString("upass"));
userList.add(user);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return userList;
}
}
6 新建 MemcachedManager.java
package memcachedTest;
import java.util.Date;
import java.util.List;
import util.UserDao;
import bean.User;
import com.alisoft.xplatform.asf.cache.memcached.client.MemCachedClient;
import com.alisoft.xplatform.asf.cache.memcached.client.SockIOPool;
public class MemcachedManager {
// 创建MemCachedClient全局对象
private static MemCachedClient mcc = new MemCachedClient();
static {
// 创建服务器列表及其权重
String[] servers = {"127.0.0.1:11211"};
Integer[] weights = {3};
// 创建Socket连接池对象
SockIOPool pool = SockIOPool.getInstance();
// 设置服务器信息
pool.setServers(servers);
pool.setWeights(weights);
pool.setFailover(true);
// 设置初始连接数、最小和最大连接数以及最大处理时间
pool.setInitConn(5);
pool.setMinConn(5);
pool.setMaxConn(250);
pool.setMaxIdle(1000*60*60*6);
// 设置主线程睡眠时间
pool.setMaintSleep(30);
// 设置TCP参数、连接超时等
pool.setNagle(false);
pool.setSocketTO(3000);
pool.setSocketConnectTO(0);
pool.setAliveCheck(true);
// 初始化连接池
pool.initialize();
// 压缩设置,超过指定大小(单位为K)的数据都会被压缩
mcc.setCompressEnable(true);
mcc.setCompressThreshold(64 * 1024);
}
/**
* 无参构造
*/
protected MemcachedManager (){
}
// 受保护的对象
protected static MemcachedManager instance = new MemcachedManager();
/**
* 为受保护的对象提供一个公共的访问方法
*/
public static MemcachedManager getInstance () {
return instance;
}
/**
* 添加对象到缓存中,构成方法重载
* @param key
* @param value
* @return
*/
public boolean add(String key,Object value) {
return mcc.add(key, value);
}
public boolean add (String key,Object value,Date expiry) {
return mcc.add(key, value,expiry);
}
public boolean replace (String key,Object value) {
return mcc.replace(key, value);
}
public boolean replace (String key,Object value,Date expiry)
{
return mcc.replace(key, value, expiry);
}
/**
* 根据指定的关键字获取对象
*/
public Object get(String key) {
return mcc.get(key);
}
/**
* 利用MemCached测试将单个对象存入缓存,并从缓存中取出
*/
// public static void main(String[] args) {
// // 得到MemcachedManager实例
// MemcachedManager cache = MemcachedManager.getInstance();
//
// // 创建UserDao对象
// UserDao userDao = new UserDao();
// // 查询单个User对象
// User user = userDao.getUserById(4);
//
// // 将User对象添加到缓存中
// cache.add("user", user.getUname());
//
// // 将User对象从缓存中取出来
// String uname = (String)cache.get("user");
//
// System.out.println("从缓存中取出的对象为:" + uname);
// }
/**
* 利用MemCached对象将集合存入缓存,并从缓存中取出
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
// 得到MemcachedManager实例
MemcachedManager cache = MemcachedManager.getInstance();
// 创建UserDao对象
UserDao userDao = new UserDao();
// 得到集合对象
List userList = userDao.getUserList();
// 创建User对象
User user = null;
for (int i=0; i<userList.size(); i++)
{
// 循环遍历集合对象
user = (User)userList.get(i);
user.getUid();
user.getUname();
user.getUpass();
// 将集合对象存入缓存中
cache.add("userList" + i,user.getUname());
// 将集合从缓存中取出
String uname = (String)cache.get("userList"+i);
System.out.println("从缓存中取得的集合为:" + uname);
}
}
}
结果从控制台输出:
从缓存中取得的集合为:uname
从缓存中取得的集合为:uname1
从缓存中取得的集合为:uname2
从缓存中取得的集合为:uname3
2 新建web project项目 名字自己取,然后导入必要的包,alisoft-xplatform-asf-cache-2.5.1.jar,commons-logging-1.0.3.jar,log4j-1.2.13.jar
3 新建类 user.java
package bean;
import java.io.Serializable;
public class User implements Serializable{
/**
* 序列号
*/
private static final long serialVersionUID = -3896605600471191953L;
private int uid;
private String uname;
private String upass;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
}
4 新建 JdbcConnector.java
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcConnector {
// 定义数据库连接常量
private final static String DRIVER = "com.mysql.jdbc.Driver";
private final static String URL = "jdbc:mysql://192.168.1.13:3306/test";
private final static String DBNAME = "root";
private final static String DBPASS = "123456";
/**
* 得到数据库连接
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public Connection getConn()throws ClassNotFoundException,SQLException {
// 加载驱动
Class.forName(DRIVER);
// 通过DriverManager对象得到连接
Connection conn = DriverManager.getConnection(URL,DBNAME,DBPASS);
// 返回数据库连接
return conn;
}
}
5 新建 UserDao.java
package util;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import bean.User;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
public class UserDao extends JdbcConnector {
// 定义全局变量
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
/**
* 根据Id查询用户
* @param uid
* @return
*/
public User getUserById(int uid) {
// 创建User对象
User user = null;
// 创建SQL语句
String sql = "select * from user where uid=?";
try {
// 获得数据库连接
conn = (Connection) this.getConn();
// 通过Connection对象创建PrepareStatement对象
pstmt = (PreparedStatement) conn.prepareStatement(sql);
// 设置SQL语句的参数
pstmt.setInt(2, uid);
// 执行查询,将查询结果赋给ResultSet对象
rs = (ResultSet) pstmt.executeQuery();
// 遍历指针
while (rs.next())
{
user = new User();
user.setUid(rs.getInt("uid"));
user.setUname(rs.getString("uname"));
user.setUpass(rs.getString("upass"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
/**
* 查询所有用户
* @return
*/
@SuppressWarnings("unchecked")
public List getUserList() {
// 创建ArrayList对象
List userList = new ArrayList();
// 创建SQL对象
String sql = "select * from user";
try {
conn = (Connection) this.getConn();
pstmt = (PreparedStatement) conn.prepareStatement(sql);
rs = (ResultSet) pstmt.executeQuery();
while (rs.next())
{
User user = new User();
user.setUid(rs.getInt("uid"));
user.setUname(rs.getString("uname"));
user.setUpass(rs.getString("upass"));
userList.add(user);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return userList;
}
}
6 新建 MemcachedManager.java
package memcachedTest;
import java.util.Date;
import java.util.List;
import util.UserDao;
import bean.User;
import com.alisoft.xplatform.asf.cache.memcached.client.MemCachedClient;
import com.alisoft.xplatform.asf.cache.memcached.client.SockIOPool;
public class MemcachedManager {
// 创建MemCachedClient全局对象
private static MemCachedClient mcc = new MemCachedClient();
static {
// 创建服务器列表及其权重
String[] servers = {"127.0.0.1:11211"};
Integer[] weights = {3};
// 创建Socket连接池对象
SockIOPool pool = SockIOPool.getInstance();
// 设置服务器信息
pool.setServers(servers);
pool.setWeights(weights);
pool.setFailover(true);
// 设置初始连接数、最小和最大连接数以及最大处理时间
pool.setInitConn(5);
pool.setMinConn(5);
pool.setMaxConn(250);
pool.setMaxIdle(1000*60*60*6);
// 设置主线程睡眠时间
pool.setMaintSleep(30);
// 设置TCP参数、连接超时等
pool.setNagle(false);
pool.setSocketTO(3000);
pool.setSocketConnectTO(0);
pool.setAliveCheck(true);
// 初始化连接池
pool.initialize();
// 压缩设置,超过指定大小(单位为K)的数据都会被压缩
mcc.setCompressEnable(true);
mcc.setCompressThreshold(64 * 1024);
}
/**
* 无参构造
*/
protected MemcachedManager (){
}
// 受保护的对象
protected static MemcachedManager instance = new MemcachedManager();
/**
* 为受保护的对象提供一个公共的访问方法
*/
public static MemcachedManager getInstance () {
return instance;
}
/**
* 添加对象到缓存中,构成方法重载
* @param key
* @param value
* @return
*/
public boolean add(String key,Object value) {
return mcc.add(key, value);
}
public boolean add (String key,Object value,Date expiry) {
return mcc.add(key, value,expiry);
}
public boolean replace (String key,Object value) {
return mcc.replace(key, value);
}
public boolean replace (String key,Object value,Date expiry)
{
return mcc.replace(key, value, expiry);
}
/**
* 根据指定的关键字获取对象
*/
public Object get(String key) {
return mcc.get(key);
}
/**
* 利用MemCached测试将单个对象存入缓存,并从缓存中取出
*/
// public static void main(String[] args) {
// // 得到MemcachedManager实例
// MemcachedManager cache = MemcachedManager.getInstance();
//
// // 创建UserDao对象
// UserDao userDao = new UserDao();
// // 查询单个User对象
// User user = userDao.getUserById(4);
//
// // 将User对象添加到缓存中
// cache.add("user", user.getUname());
//
// // 将User对象从缓存中取出来
// String uname = (String)cache.get("user");
//
// System.out.println("从缓存中取出的对象为:" + uname);
// }
/**
* 利用MemCached对象将集合存入缓存,并从缓存中取出
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
// 得到MemcachedManager实例
MemcachedManager cache = MemcachedManager.getInstance();
// 创建UserDao对象
UserDao userDao = new UserDao();
// 得到集合对象
List userList = userDao.getUserList();
// 创建User对象
User user = null;
for (int i=0; i<userList.size(); i++)
{
// 循环遍历集合对象
user = (User)userList.get(i);
user.getUid();
user.getUname();
user.getUpass();
// 将集合对象存入缓存中
cache.add("userList" + i,user.getUname());
// 将集合从缓存中取出
String uname = (String)cache.get("userList"+i);
System.out.println("从缓存中取得的集合为:" + uname);
}
}
}
结果从控制台输出:
从缓存中取得的集合为:uname
从缓存中取得的集合为:uname1
从缓存中取得的集合为:uname2
从缓存中取得的集合为:uname3
推荐阅读
-
缓存Redis与Memcached的比较
-
java缓存(MemChachedClient)
-
Java基础,java缓存读写文件小例子
-
Java获取客户端代码大全(转)
-
java缓存
-
JAVA 入坑教程 | 章节七 条件分支结构
-
究竟先操作缓存,还是数据库?
-
javascript - wx.request请求结果如何强制不使用缓存?
-
伪分布式内存缓存之Memcached
-
【转 Tomcat集群session管理解决方案(关于sticky session、session replication与使用memcached缓存sess tomcatmemcachedsticky sessionnon sticky session