昨天已經在windows環境下安裝使用了redis。
下面准備在java項目中測試使用redis。
redis官網推薦使用jedis來訪問redis。所以首先准備了jedis的jar包,以及需要依賴的jar包。
commons-pool2-2.3
hamcrest-core-1.3
jedis-2.7.2.jar
因為redis也是屬於一種數據庫,也是對數據的訪問,所以把他放置在dao層,與service分開
import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import com.dyuproject.protostuff.LinkedBuffer; import com.dyuproject.protostuff.ProtostuffIOUtil; import com.dyuproject.protostuff.runtime.RuntimeSchema; import com.xhxkj.ssm.entity.UserEntity; /** * 訪問redis數據層 * @author XX * */ public class RedisDao { private final JedisPool jedisPool;//redis連接池 /** * 構造方法 * @param ip 訪問的ip * @param port 訪問的端口 */ public RedisDao(String ip, int port) { jedisPool = new JedisPool(ip,port); } //創建一個schema用來序列化 private RuntimeSchema<UserEntity> schema = RuntimeSchema.createFrom(UserEntity.class); /** * 通過用戶名獲取redis中對應的用戶信息 * @param username 輸入的用戶名 * @return 存在返回:這個對象,不存在返回:null */ public UserEntity getUser(String username) { //redis操作 try{ Jedis jedis = jedisPool.getResource(); try { //在redis中存放時,key的書寫規則,官方推薦,對象:對象屬性 //也就是獲取時利用“user:username”作為鍵來得到值 String key = "user:" + username; //自定義序列化 //在redis中獲取的值一定是一個字節數組,需要通過反序列化轉換成java對象 byte[] bytes = jedis.get(key.getBytes()); if(bytes != null) { //獲取一個空對象 UserEntity user = schema.newMessage(); //反序列化后放置在user中 ProtostuffIOUtil.mergeFrom(bytes, user, schema); return user; } }finally{ jedis.close(); } }catch (Exception e){ e.printStackTrace(); } return null; } /** * 在緩存中存放user對象 * @param user * @return 成功返回“OK”;失敗返回錯誤信息 */ public String putUser(UserEntity user) { try { Jedis jedis = jedisPool.getResource(); try { //通過對應的鍵存放user對象 String key = "user:" + user.getUsername(); //自定義序列化操作,利用protostuff將對象序列化成字節數組 byte[] bytes = ProtostuffIOUtil.toByteArray(user, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE)); //緩存時間1小時,緩存的時間是用秒來計的 int timeout = 60*60; //在redis中存放這個對象 return jedis.setex(key.getBytes(),timeout,bytes); } finally{ jedis.close(); } } catch (Exception e) { e.printStackTrace(); } return null; } }
這里提供了兩個方法,分別是put和get,其中需要用到序列化和反序列化的操作,用到的jar包有下面這幾個
protostuff-core-1.0.8.jar
protostuff-runtime-1.0.8.jar
protostuff-collectionschema-1.0.8.jar
protostuff-api-1.0.8.jar
protostuff屬於性能相當優秀的一種
在spring中配置
<!-- redisDao -->
<bean id="redisDao" class="com.xxx.dao.redis.RedisDao">
<constructor-arg index="0" value="localhost"/>
<constructor-arg index="1" value="6379"/>
</bean>
之后就可以直接在服務層調用redisDao的方法了
//首先去redis中尋找是否存在緩存的用戶信息
UserEntity resultUser = redisDao.getUser("xx");
//如果不存在,那就在緩存中放置一個用戶信息
if(resultUser == null)
{
String result = redisDao.putUser(user);
System.out.println(result);
return null;
}
else
{
return resultUser;
}
需要注意的是,如果存放成功,返回是一個字符串“OK”
在使用前一定要確定你的redis服務處於開啟狀態,cmd窗口是開着的
因為網絡上面很多都是用maven配置的,所以jar包比較難找,jar包間的依賴確實比較麻煩,推薦一個網站http://maven.outofmemory.cn/
這個網站能很好的找到各種jar包,並且告訴你依賴的關系,非常方便
