1.配置文件:redis.properties
redis.host=127.0.0.1
redis.port=6379
redis.password=""
redis.maxIdle=50
redis.maxTotal=100
redis.maxWaitMillis=1000
redis.blockWhenExhausted=true
redis.testOnBorrow=true
redis.timeout=10000
defaultCacheExpireTime=60
2.applicationContext.xml:其中包含spring,mybatis,redis的配置
** <context:property-placeholder location=“classpath:db.properties,classpath:redis.properties”/>**
整个项目只能有这样一个文件引入配置生效,文件中出现两个会报Could not resolve placeholder的异常
<!-- redis配置 非集群式-->
<!-- 导入spring-redis配置文件 -->
<!-- redis数据源 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最大空闲数 -->
<property name="maxIdle" value="${redis.maxIdle}" />
<!-- 最大连接数 -->
<property name="maxTotal" value="${redis.maxTotal}" />
<!-- 最大等待时间 -->
<property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
<!-- 连接超时时是否阻塞,false时报异常,true阻塞到直到超时,默认true -->
<property name="blockWhenExhausted" value="${redis.blockWhenExhausted}"/>
<!-- 返回连接时,检测连接是否成功 -->
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
</bean>
<!-- Spring整合Jedis -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<!-- 指定连接地址 -->
<property name="hostName" value="127.0.0.1"/>
<!-- 指定端口号 -->
<property name="port" value="6379"/>
<!-- 自定义连接池的配置 -->
<property name="poolConfig" ref="poolConfig"/>
</bean>
<!-- RedisTempLate -->
<bean class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"/>
</bean>
3.实际应用:
1.list类型的添加,取出
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {
@Autowired
private RedisTemplate template;
@Test
public void TestList() {
List<String>list1=new ArrayList<String>();
list1.add("aaa");
list1.add("bbb");
list1.add("ccc");
list1.add("ddd");
template.opsForList().leftPush("list1", list1);
System.out.println(template.opsForList().rightPop("list1"));
}
2.判断key是否存在:
template.hasKey(key)//:判断大的类型;
template.opsForHash().hasKey(key, hashKey)
//key等同于上面的那个key,hashKey代表key里面记录代表的key;
//如:template.opsForHash().put("member", po.getMno(), po);member相当于一个表,po.getMno()
//相当于表里面的每条记录的主键,po代表整条纪录.
3.使用场景:
1.string:保证二进制安全,可以存任何数据
2.list:可以用来消息队列,template.opsForList().rightPopAndLeftPush(sourceKey, destinationKey):将sourceKey里面的最后一个元素添加到destinationKey的最前面;
3.set:
(1)可以用来实现随机抽奖: template.opsForSet().randomMembers(key, count);抽取key中的count个元素,count可不写,默认为1;
(2)判断用户,或某个信息是否存在template.opsForSet().isMember(key, 元素值);
4.zset:排行版和任务执行优先级;