您的位置:首页 > 数据库 > Redis

Spring Data Redis 使用redis的一些方法点

2016-12-14 16:32 603 查看
在applicationContext,xml中设置 spring 的redis的使用配置信息

<!--jedis的连接池配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最大空闲连接数量 -->
<property name="maxIdle" value="100" />
<!-- 最小空闲连接数量, 处理间隔时间为 timeBetweenEvictionRunsMillis -->
<property name="minIdle" value="10" />
<!-- 池中持有的最大连接数量 -->
<property name="maxTotal" value="50" />
<!-- borrowObject 方法的最大等待时间 -->
<property name="maxWaitMillis" value="10" />
<!-- 池中可用资源耗尽时, borrow 方法是否阻塞等待 maxWaitMillis 毫秒 -->
<property name="blockWhenExhausted" value="true" />
<!-- borrowObject 时是否执行检测 -->
<property name="testOnBorrow" value="true" />
<!-- 是否检测空闲连接链接的有效性, 间隔时间为 timeBetweenEvictionRunsMillis -->
<property name="testWhileIdle" value="true" />
<!-- 空闲对象被清除需要达到的最小空闲时间 -->
<property name="minEvictableIdleTimeMillis" value="1000" />
<!-- 空闲检测线程,sleep 间隔多长时间,去处理与idle相关的事情 -->
<property name="timeBetweenEvictionRunsMillis" value="1000" />
</bean>
<!-- jedis的连接工厂 -->
<bean id="connectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="192.168.1.120" />
<property name="port" value="16379" />
<property name="database" value="1" />
<property name="password" value="XXXXXX" />
<property name="timeout" value="2000" />
<!-- <property name="poolConfig" value="poolConfig"/> -->
</bean>
<!--redis实际使用的template -->
<!-- 类似于spring提供的HibernateDaoSupport -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="keySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<!-- <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"
/> -->
<!-- <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"
/> -->
<bean
class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
</property>
</bean>
<!-- end -->


其中 redisTemplate 的bean配置,就指定了key和value序列化的实现类

2. 在java 源码中对数据进行存取的代码

注入RedisTemplate 和ValueOperations

其中Passport类是自定义的类,对应于redis 中一个value的对象

@Autowired
private RedisTemplate<String, Passport> redisTemplate;
@Resource(name = "redisTemplate")
private ValueOperations<String, Passport> operations;


根据key获取value

redisTemplate.opsForValue().get("key")


把value的对象保存在一个key对应的value里面

redisTemplate.boundValueOps(passport.getMobile()).set(passport)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring redis