由於之前對redis有了一個系統的研究,在公司的多個項目中使用redis當做數據緩存;所以趁着這些天晚上的時間,自己寫了一個demo;這裏僅供自己後期學習筆記參考,若有不對的地方,請輕拍磚!
redis 官網推薦給java 使用的客戶端很多:Jedis、Redisson、JRedis、JDBC-Redis 等,當然首推是jedis;可以參考redis客戶端官網查看。
接下來來講下我的這個demo,我這個案例不是通過spring進行整合的redis,這個將會在之後的demo中講到的。
(1).創建一個maven 功臣,在工程的pom 中引入jedis客戶端;還有要依賴spring管理,所以也要引入spring相關jar包。
- <span style="white-space:pre"> </span><dependency>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- <version>${jedis-version}</version>
- </dependency>
- <dependency>
(2).一般一個(系統)項目所用的redis服務器 多節點的集羣服務器,所以會自己對(jedis)redis客戶端進行封裝,由於本例我自己寫的是單節點,但是我還是按多節點的思路對客戶端進行了封裝。
redisClient類
- /**
- * redis 客戶端封裝
- * @author leo
- *
- */
- public class RedisClient {
- /**
- * 日誌記錄
- */
- private static final Log LOG = LogFactory.getLog(RedisClient.class);
- /**
- * redis 連接池
- */
- private JedisPool pool;
- public void setPool(JedisPool pool) {
- this.pool = pool;
- }
- /**
- * 獲取jedis
- * @return
- */
- public Jedis getResource(){
- Jedis jedis =null;
- try {
- jedis =pool.getResource();
- } catch (Exception e) {
- LOG.info("can't get the redis resource");
- }
- return jedis;
- }
- /**
- * 關閉連接
- * @param jedis
- */
- public void disconnect(Jedis jedis){
- jedis.disconnect();
- }
- /**
- * 將jedis 返還連接池
- * @param jedis
- */
- public void returnResource(Jedis jedis){
- if(null != jedis){
- try {
- pool.returnResource(jedis);
- } catch (Exception e) {
- LOG.info("can't return jedis to jedisPool");
- }
- }
- }
- /**
- * 無法返還jedispool,釋放jedis客戶端對象,
- * @param jedis
- */
- public void brokenResource(Jedis jedis){
- if (jedis!=null) {
- try {
- pool.returnBrokenResource(jedis);
- } catch (Exception e) {
- LOG.info("can't release jedis Object");
- }
- }
- }
- }
- <!-- jedis 連接池配置參數: -->
- <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
- <property name="maxActive" value="100"></property>
- <property name="maxIdle" value="25"></property>
- <property name="maxWait" value="15000"></property>
- <property name="testOnBorrow" value="false"></property>
- <property name="testOnReturn" value="false"></property>
- </bean>
- <!-- jedis 連接池 連接本地redis服務 構造器注入-->
- <bean id="pool" class="redis.clients.jedis.JedisPool">
- <constructor-arg index="0" ref="poolConfig"/>
- <constructor-arg index="1" value="10.224.68.46"/>
- <constructor-arg index="2" value="6379"/>
- <constructor-arg index="3" value="2000"/>
- </bean>
- <!-- cleint-->
- <bean id="redisClient" class="com.deppon.cache.redis.RedisClient">
- <property name="pool" ref="pool"/>
- </bean>
存儲器接口:
- /**
- *
- * @author leo
- *緩存存儲接口
- * @param <K> key
- * @param <V> value
- */
- public interface RedisCacheStorage<K, V> {
- /**
- * 在redis數據庫中插入 key 和value
- * @param key
- * @param value
- * @return
- */
- boolean set(K key,V value);
- /**
- * 在redis數據庫中插入 key 和value 並且設置過期時間
- * @param key
- * @param value
- * @param exp 過期時間 s
- * @return
- */
- boolean set(K key, V value, int exp);
- /**
- * 根據key 去redis 中獲取value
- * @param key
- * @return
- */
- V get(K key);
- /**
- * 刪除redis庫中的數據
- * @param key
- * @return
- */
- boolean remove(K key);
- /**
- * 設置哈希類型數據到redis 數據庫
- * @param cacheKey 可以看做一張表
- * @param key 表字段
- * @param value
- * @return
- */
- boolean hset(String cacheKey,K key,V value);
- /**
- * 獲取哈希表數據類型的值
- * @param cacheKey
- * @param key
- * @return
- */
- V hget(String cacheKey,K key);
- /**
- * 獲取哈希類型的數據
- * @param cacheKey
- * @return
- */
- Map<K,V> hget(String cacheKey);
- /**
- * redis 緩存存儲器實現
- * @author leo
- *
- * @param <V>
- */
- public class RedisCacheStorageImpl<V> implements RedisCacheStorage<String, V> {
- /**
- * 日誌記錄
- */
- public static final Log LOG = LogFactory.getLog(RedisCacheStorageImpl.class);
- /**
- * redis 客戶端
- */
- private RedisClient redisClient;
- /**
- * 默認過時時間
- */
- private static final int EXPRIE_TIME =3600*24;
- public void setRedisClient(RedisClient redisClient) {
- this.redisClient = redisClient;
- }
- /**
- * 在redis數據庫中插入 key 和value
- * @param key
- * @param value
- * @return
- */
- @Override
- public boolean set(String key, V value) {
- //設置默認過時時間
- return set(key, value, EXPRIE_TIME);
- }
- /**
- * 在redis數據庫中插入 key 和value 並且設置過期時間
- * @param key
- * @param value
- * @param exp 過期時間 s
- * @return
- */
- @SuppressWarnings("finally")
- @Override
- public boolean set(String key, V value, int exp) {
- Jedis jedis =null;
- //將key 和value 轉換成 json 對象
- String jKey =CacheUtils.toJsonString(key);
- String jValue =CacheUtils.toJsonString(value);
- //操作是否成功
- boolean isSucess =true;
- if(StringUtils.isNotEmpty(jKey)){
- LOG.info("key is empty");
- return false;
- }
- try {
- //獲取客戶端對象
- jedis =redisClient.getResource();
- //執行插入
- jedis.setex(jKey, exp, jValue);
- } catch (JedisException e) {
- LOG.info("client can't connect server");
- isSucess =false;
- if(null !=jedis){
- //釋放jedis對象
- redisClient.brokenResource(jedis);
- }
- return false;
- }finally{
- if(isSucess){
- //返還連接池
- redisClient.returnResource(jedis);
- }
- return true;
- }
- }
- /**
- * 根據key 去redis 中獲取value
- * @param key
- * @return
- */
- @SuppressWarnings("unchecked")
- @Override
- public V get(String key) {
- Jedis jedis =null;
- //將key 和value 轉換成 json 對象
- String jKey =CacheUtils.toJsonString(key);
- V jValue =null;
- //key 不能爲空
- if(StringUtils.isEmpty(jKey)){
- LOG.info("key is empty");
- return null;
- }
- try {
- //獲取客戶端對象
- jedis =redisClient.getResource();
- //執行查詢
- String value = jedis.get(jKey);
- //判斷值是否非空
- if(StringUtils.isEmpty(value)){
- return null;
- }else{
- jValue= (V) CacheUtils.jsonParseObject(value);
- }
- //返還連接池
- redisClient.returnResource(jedis);
- } catch (JedisException e) {
- LOG.info("client can't connect server");
- if(null !=jedis){
- //釋放jedis 對象
- redisClient.brokenResource(jedis);
- }
- }
- return jValue;
- }
- /**
- * 刪除redis庫中的數據
- * @param key
- * @return
- */
- @SuppressWarnings("finally")
- @Override
- public boolean remove(String key) {
- Jedis jedis =null;
- //將key 和value 轉換成 json 對象
- String jKey =CacheUtils.toJsonString(key);
- //操作是否成功
- boolean isSucess =true;
- if(StringUtils.isEmpty(jKey)){
- LOG.info("key is empty");
- return false;
- }
- try {
- jedis =redisClient.getResource();
- //執行刪除
- jedis.del(jKey);
- } catch (JedisException e) {
- LOG.info("client can't connect server");
- isSucess =false;
- if(null !=jedis){
- //釋放jedis 對象
- redisClient.brokenResource(jedis);
- }
- return false;
- }finally{
- if (isSucess) {
- //返還連接池
- redisClient.returnResource(jedis);
- }
- return true;
- }
- }
- /**
- * 設置哈希類型數據到redis 數據庫
- * @param cacheKey 可以看做一張表
- * @param key 表字段
- * @param value
- * @return
- */
- @SuppressWarnings("finally")
- @Override
- public boolean hset(String cacheKey, String key, V value) {
- Jedis jedis =null;
- //將key 和value 轉換成 json 對象
- String jKey =CacheUtils.toJsonString(key);
- String jCacheKey =CacheUtils.toJsonString(cacheKey);
- String jValue =CacheUtils.toJsonString(value);
- //操作是否成功
- boolean isSucess =true;
- if(StringUtils.isEmpty(jCacheKey)){
- LOG.info("cacheKey is empty");
- return false;
- }
- try {
- jedis =redisClient.getResource();
- //執行插入哈希
- jedis.hset(jCacheKey, jKey, jValue);
- } catch (JedisException e) {
- LOG.info("client can't connect server");
- isSucess =false;
- if(null !=jedis){
- //釋放jedis 對象
- redisClient.brokenResource(jedis);
- }
- return false;
- }finally{
- if (isSucess) {
- //返還連接池
- redisClient.returnResource(jedis);
- }
- return true;
- }
- }
- /**
- * 獲取哈希表數據類型的值
- * @param cacheKey
- * @param key
- * @return
- */
- @SuppressWarnings("unchecked")
- @Override
- public V hget(String cacheKey, String key) {
- Jedis jedis =null;
- //將key 和value 轉換成 json 對象
- String jKey =CacheUtils.toJsonString(key);
- String jCacheKey =CacheUtils.toJsonString(cacheKey);
- V jValue =null;
- if(StringUtils.isEmpty(jCacheKey)){
- LOG.info("cacheKey is empty");
- return null;
- }
- try {
- //獲取客戶端對象
- jedis =redisClient.getResource();
- //執行查詢
- String value = jedis.hget(jCacheKey, jKey);
- //判斷值是否非空
- if(StringUtils.isEmpty(value)){
- return null;
- }else{
- jValue= (V) CacheUtils.jsonParseObject(value);
- }
- //返還連接池
- redisClient.returnResource(jedis);
- } catch (JedisException e) {
- LOG.info("client can't connect server");
- if(null !=jedis){
- //釋放jedis 對象
- redisClient.brokenResource(jedis);
- }
- }
- return jValue;
- }
- /**
- * 獲取哈希類型的數據
- * @param cacheKey
- * @return
- */
- @Override
- public Map<String, V> hget(String cacheKey) {
- String jCacheKey =CacheUtils.toJsonString(cacheKey);
- //非空校驗
- if(StringUtils.isEmpty(jCacheKey)){
- LOG.info("cacheKey is empty!");
- return null;
- }
- Jedis jedis =null;
- Map<String,V> result =null;
- try {
- jedis =redisClient.getResource();
- //獲取列表集合
- Map<String,String> map = jedis.hgetAll(jCacheKey);
- if(null !=map){
- for(Map.Entry<String, String> entry : map.entrySet()){
- if(result ==null){
- result =new HashMap<String,V>();
- }
- result.put((String) CacheUtils.jsonParseObject(entry.getKey()), (V)CacheUtils.jsonParseObject(entry.getValue()));
- }
- }
- } catch (JedisException e) {
- LOG.info("client can't connect server");
- if(null !=jedis){
- //釋放jedis 對象
- redisClient.brokenResource(jedis);
- }
- }
- return result;
- }
- }
創建UserEntity實體類:
- /**
- * 用戶實體類
- * @author leo
- *
- */
- public class UserEntity {
- //用戶id
- private String userId;
- //用戶賬號
- private String EmpCode;
- //用戶名稱
- private String EmpName;
- //用戶角色
- private String role;
- //職位
- private String title;
- public String getUserId() {
- return userId;
- }
- public void setUserId(String userId) {
- this.userId = userId;
- }
- public String getEmpCode() {
- return EmpCode;
- }
- public void setEmpCode(String empCode) {
- EmpCode = empCode;
- }
- public String getEmpName() {
- return EmpName;
- }
- public void setEmpName(String empName) {
- EmpName = empName;
- }
- public String getRole() {
- return role;
- }
- public void setRole(String role) {
- this.role = role;
- }
- public String getTitle() {
- return title;
- }
- public void setTitle(String title) {
- this.title = title;
- }
userServiceImpl類:
- /**
- * 業務層接口實現
- * @author leo
- *
- */
- public class UserServiceImpl implements IUserService {
- private static final String cacheKey ="userEntity";
- /**
- * 緩存存儲
- */
- private RedisCacheStorageImpl<UserEntity> storageCache;
- public void setStorageCache(RedisCacheStorageImpl<UserEntity> storageCache) {
- this.storageCache = storageCache;
- }
- /**
- * 新增
- * @param entity
- * @return
- */
- @Override
- public boolean addUserEntity(UserEntity entity) {
- //非空
- if(entity ==null || StringUtils.isEmpty(entity.getUserId())){
- return false;
- }
- /**
- * 做數據庫持久化,這裏就無需再申明瞭
- */
- System.out.println("先插入數據庫中,.........");
- //然後接下來做非關係型數據庫持久化
- return storageCache.hset(cacheKey, entity.getUserId(), entity);
- }
- @Override
- public boolean deleteUserEntity(UserEntity entity) {
- return false;
- }
- /**
- * 根據id 查詢
- * @return
- */
- @Override
- public UserEntity queryUserEntityByUserId(UserEntity userEntity) {
- //非空
- if(userEntity ==null || StringUtils.isEmpty(userEntity.getUserId())){
- return null;
- }
- //先去緩存中查詢 是否存在,不存在在查詢
- UserEntity reslut = storageCache.hget(cacheKey, userEntity.getUserId());
- if(reslut!=null){
- return reslut;
- }else{
- //查詢數據庫
- System.out.println("查詢數據庫");
- }
- return null;
- }
- }
- <!-- storge Cache 存儲器-->
- <bean id="storageCache" class="com.deppon.cache.storage.impl.RedisCacheStorageImpl">
- <property name="redisClient" ref="redisClient" />
- </bean>
- <bean id="userServiceImpl" class="com.deppon.cache.service.impl.UserServiceImpl">
- <property name="storageCache" ref="storageCache"/>
- </bean>
- public class TestUserServiceImpl {
- /**
- * 用戶接口
- */
- private IUserService userServiceImpl;
- public void setUserServiceImpl(IUserService userServiceImpl) {
- this.userServiceImpl = userServiceImpl;
- }
- @Before
- public void setUp() throws Exception {
- userServiceImpl = (IUserService) SpringTestHelper.get().getBeanByClass(UserServiceImpl.class);
- }
- @After
- public void tearDown() throws Exception {
- }
- @Test
- public void testAdd(){
- UserEntity entity = new UserEntity();
- entity.setUserId("000001");
- entity.setEmpCode("130566");
- entity.setEmpName("leonardo-zeng");
- entity.setRole("Java Development Engineer");
- entity.setTitle("PM");
- boolean isTrue =userServiceImpl.addUserEntity(entity);
- Assert.assertTrue(isTrue);
- }
- @Test
- public void testQueryById(){
- UserEntity entity = new UserEntity();
- entity.setUserId("000001");
- UserEntity userEntity =userServiceImpl.queryUserEntityByUserId(entity);
- System.out.println(userEntity);
- }
- }
redis 127.0.0.1:6379> hkeys "\"userEntity\""
1) "\"000001\""
redis 127.0.0.1:6379> hget "\"userEntity\"" "\"000001\""
"{\"@type\":\"com.deppon.cache.entity.UserEntity\",\"empCode\":\"130566\",\"empN
ame\":\"leonardo-zeng\",\"role\":\"Java Development Engineer\",\"title\":\"PM\",
\"userId\":\"000001\"}"
redis 127.0.0.1:6379>
整個demo就這樣了