Redis配置規范


1 簡介

Redis本質上是一個Key-Value類型的內存數據庫,很像memcached,整個數據庫統統加載在內存當中進行操作,定期通過異步操作把數據庫數據flush到硬盤上進行保存。因為是純內存操作,Redis的性能非常出色,每秒可以處理超過 10萬次讀寫操作,是已知性能最快的Key-Value DB。

詳細介紹可參考:Redis設計與實現

2 配置

2.1 配置文件

與Spring整合,通常使用 applicationContext-redis.xml 作為Redis配置文件的命名,web.xml會自動掃描並加載

2.2 配置說明

2.2.1 JedisPoolConfig

連接池的配置

maxIdle:最大空閑連接數

maxTotal:最大連接數

maxWaitMillis:最大等待時間

testOnBorrow:

2.2.2 JedisConnectionFactory

連接工廠

hostName:redis服務器地址

port:redis服務器端口

usePool:是否使用連接池

poolConfig-ref:連接池配置引用

2.2.3 StringRedisTemplate

使用模板:

connectionFactory-ref:連接工程引用

2.3 示例

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:p="http://www.springframework.org/schema/p"
      xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
       <property name="maxIdle" value="300" />
       <property name="maxTotal" value="1000" />
       <property name="MaxWaitMillis" value="1000" />
       <property name="testOnBorrow" value="true" />
   </bean>

   <bean id="jedisConnFactory"
         class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
         p:hostName="${redis.host}" p:port="${redis.port}" p:usePool="true" p:poolConfig-ref="poolConfig" />

   <bean id="stringRedisTemplate"
         class="org.springframework.data.redis.core.StringRedisTemplate"
         p:connectionFactory-ref="jedisConnFactory"/>

</beans>

3 使用

// 注入Redis
@Autowired
private RedisTemplate<String,Object> redisTemplate;

public void demo () {
   // 字符串用法
   redisTemplate.opsForValue().set("key", "val");
    redisTemplate.opsForValue().set("key", "val", times);
    redisTemplate.opsForValue().set("key", "val", times, timeUnit);
    redisTemplate.opsForValue().get("key");

   // 哈希表(map)用法
   redisTemplate.opsForHash().put("key", "mapKey1", "val1");
    redisTemplate.opsForHash().put("key", "mapKey2", "val2");
    redisTemplate.opsForHash().get("key", "mapKey1");        
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM