Redis應用總結

來源:互聯網
上載者:User

1. 安裝

$ wget http://redis.googlecode.com/files/redis-2.6.14.tar.gz$ tar xzf redis-2.6.14.tar.gz$ cd redis-2.6.14$ make $ make install

啟動服務:
/usr/local/bin/redis-server

用戶端命令:
/usr/local/bin/redis-cli

2. 配置

在源檔案  redis-2.6.14/utils 下有一個 redis_init_script 可以做為redis的啟動指令檔

REDISPORT=6379 #連接埠號碼
EXEC=/usr/local/bin/redis-server
CLIEXEC=/usr/local/bin/redis-cli

PIDFILE=/var/run/redis_${REDISPORT}.pid
CONF="/usr/local/redis/redis.conf"  #設定檔地址

可以 修改 REDISPORT=6379 和 CONF

在 redis-2.6.14 有一個 redis.conf 的設定檔,裡邊可以主要配置

port 6379  #連接埠號碼

daemonize yes  #後台運行

dir /mnt/redisdata  #配置持久化檔案存放的地方

maxclients 5000  # 最大的用戶端串連數

maxmemory 1500000000  #最大使用記憶體<1.5G>

requirepass mypass # 訪問串連密碼

然後把 執行指令碼和設定檔放在某目錄下,如

/usr/local/redis/bin/redis_init_script 
/usr/local/redis/redis.conf 

3.  運行和停止

運行  /usr/local/redis/bin/redis_init_script  start  /usr/local/redis/redis.conf 

停止   /usr/local/redis/bin/redis_init_script  stop /usr/local/redis/redis.conf 

4. spring 和 redis整合

 <!-- jedis pool配置 -->      <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">          <property name="maxActive" value="1024" />          <property name="maxIdle" value="200" />          <property name="maxWait" value="1000" />          <property name="testOnBorrow" value="true" />      </bean>        <!-- spring data redis -->      <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">          <property name="usePool" value="true" />        <property name="hostName" value="192.168.0.111" />          <property name="port" value="6379" />          <property name="password" value="" />          <property name="timeout" value="100000" />          <constructor-arg index="0" ref="jedisPoolConfig" />      </bean>            <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">          <property name="connectionFactory" ref="jedisConnectionFactory" />      </bean>         <bean id="redisBase" abstract="true" class="com.itmg.cache.impl.RedisBase">     <property name="redisTemplateBase" ref="redisTemplate" />      </bean>         <bean id="redisCacheBase" class="com.itmg.cache.impl.RedisCacheBase">     <property name="template" ref="redisTemplate" />     </bean>          <bean id="searchCacheService" class="com.itmg.cache.impl.SearchCacheServiceImpl" parent="redisCacheBase"/>     <bean id="updateCacheService" class="com.itmg.cache.impl.UpdateCacheServiceImpl" parent="redisCacheBase"/>

package com.cache.impl;import java.util.ArrayList;import java.util.List;import org.springframework.dao.DataAccessException;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.core.RedisCallback;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.RedisSerializer;import com.model.KeywordsModel;import com.vo.AwsDataVO;/** *  * @author Administrator * */public class RedisCacheBase {private RedisTemplate template;public RedisCacheBase() {// TODO Auto-generated constructor stub}/** * 讀取緩衝 * @param key * @return */public Object readCache(final String key){Object result = (Object)template.execute(new RedisCallback<Object>() {              public Object doInRedis(RedisConnection connection) throws DataAccessException {                  RedisSerializer<String> serializer = template.getDefaultSerializer();                  byte[] keyByte = serializer.serialize(key);                  byte[] value = connection.get(keyByte);                  if (value == null) {                      return null;                  }                  Object u = (Object)template.getDefaultSerializer().deserialize(value);                return u;              }          });          return result;}/** * 讀取緩衝 * @param key * @return */public List<Object> readListCache(final String key){List<Object> objList = (List<Object>)template.execute(new RedisCallback<Object>() {              public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {                  RedisSerializer<String> serializer = template.getDefaultSerializer();                  byte[] keyByte = serializer.serialize(key);                long length = connection.lLen(keyByte);                List<byte[]> values = connection.lRange(keyByte, 0, length);                if (values == null) {                      return null;                  }                List<Object> objList = new ArrayList<Object>();                for(byte[] value : values){                 Object u = (Object)template.getDefaultSerializer().deserialize(value);                 objList.add(u);                }                connection.del(keyByte);                return objList;              }          });          return objList;}/** * 添加單個元素至列表 * @param key * @param value * @param liveTime * @return */public boolean addAObjectToList(final String key, final Object value,final Integer liveTime){boolean result = (Boolean)template.execute(new RedisCallback<Boolean>() {      public Boolean doInRedis(RedisConnection connection) throws DataAccessException {              RedisSerializer serializer = template.getDefaultSerializer();    byte[] keys  = serializer.serialize(key);      byte[] objVal = serializer.serialize(value);    connection.lPush(keys, objVal);    /*if (null != liveTime && liveTime > 0) {    connection.expire(keys, liveTime);}*/    return true;      }  });  return result;}/** * 建立或更新緩衝 * @param key * @param value * @param liveTime * @return */public boolean saveCache(final String key, final Object value,final Integer liveTime){boolean result = (Boolean)template.execute(new RedisCallback<Boolean>() {      public Boolean doInRedis(RedisConnection connection) throws DataAccessException {              RedisSerializer serializer = template.getDefaultSerializer();    byte[] keys  = serializer.serialize(key);      byte[] objVal = serializer.serialize(value);    connection.set(keys, objVal);    if (null != liveTime && liveTime > 0) {    connection.expire(keys, liveTime);}    return true;      }  });  return result;}/** * 刪除緩衝,單個 * @param key * @return */public boolean removeCache(final String key){boolean result = (Boolean)template.execute(new RedisCallback<Boolean>() {      public Boolean doInRedis(RedisConnection connection) throws DataAccessException {              RedisSerializer serializer = template.getDefaultSerializer();    byte[] keys  = serializer.serialize(key);      connection.del(keys);    return true;      }  });  return result;}public RedisTemplate getTemplate() {return template;}public void setTemplate(RedisTemplate template) {this.template = template;}}

package com.cache.impl;import java.util.List;import com.cache.SearchCacheService;import com.model.KeywordsModel;import com.util.Constants;import com.vo.AwsDataVO;import com.vo.SearchResultVO;public class SearchCacheServiceImpl extends RedisCacheBase implements SearchCacheService {public List<KeywordsModel> getIndexPageWordList() throws Exception {Object obj = readCache(Constants.CACHE_NAME_INDEX_PAGE);if(obj != null){List<KeywordsModel> indexPageList = (List<KeywordsModel>)obj;return indexPageList;}return null;}public SearchResultVO getSearchResultVO(String conditionMD5)throws Exception {Object obj = readCache(Constants.CACHE_NAME_SEARCH_RESULT+conditionMD5);if(obj != null){SearchResultVO searchResultVO = (SearchResultVO)obj;return searchResultVO;}return null;}public List<AwsDataVO> getAmazonIndexData() throws Exception {Object obj = readListCache(Constants.CACHE_NAME_SAVE_CREATE_INDEX);if(obj != null){return (List<AwsDataVO>)obj;}return null;}public List<KeywordsModel> getKeywordsList() throws Exception {Object obj = readListCache(Constants.CACHE_NAME_SAVE_FILTER_KEYWORDS);if (obj != null) {return (List<KeywordsModel>)obj;}return null;}}

package com.cache.impl;import java.util.List;import com.cache.UpdateCacheService;import com.model.KeywordsModel;import com.util.Constants;import com.vo.AwsDataVO;import com.vo.SearchResultVO;public class UpdateCacheServiceImpl extends RedisCacheBase implements UpdateCacheService {private Object objectkeywords = new Object();private Object objectindex = new Object();public void saveIndexPageWordList(List<KeywordsModel> keywordsModellist)throws Exception {saveCache(Constants.CACHE_NAME_INDEX_PAGE, keywordsModellist, 3600*24);}public void saveSearchResultVO(String conditionMD5,SearchResultVO searchResultVO) throws Exception {saveCache(Constants.CACHE_NAME_SEARCH_RESULT+conditionMD5, searchResultVO, 3600*24*5);}public void saveAmazonIndexData(List<AwsDataVO> awsDataModelList) throws Exception {synchronized (objectindex) {for(AwsDataVO awsDataVO : awsDataModelList){addAObjectToList(Constants.CACHE_NAME_SAVE_CREATE_INDEX, awsDataVO, 3600*24*2);}}}public void saveKeywordsList(List<KeywordsModel> keywordsModelList)throws Exception {synchronized (objectkeywords) {for(KeywordsModel keywordsModel : keywordsModelList){addAObjectToList(Constants.CACHE_NAME_SAVE_FILTER_KEYWORDS, keywordsModel, 3600*24*2);}}}}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.