哈希里面存的都是string类型的key和value
一:命令行
二: spring中使用
1.配置文件spring-mvc-redis.xml
<mvc:annotation-driven/>
<context:component-scan base-package="Dao,Tenseven"/>
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="50"/>
<property name="maxTotal" value="100"/>
<property name="maxWaitMillis" value="20000"/>
</bean>
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="localhost"/>
<property name="port" value="6379"/>
<property name="poolConfig" ref="poolConfig"/>
</bean>
<bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="defaultSerializer" ref="stringRedisSerializer"/>方法1
<property name="hashKeySerializer" ref="stringRedisSerializer"/>方法2 <property name="hashValueSerializer" ref="stringRedisSerializer"/>
</bean>
- 可以通过设置hashKeySerializer和hashValueSerializer设置哈希的序列化
- 如果不想设置,也可以设置默认序列化器
2.运行方法
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-mvc-redis.xml")
public class test1 {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void hashRedisTest() {
Map map = new HashMap();
map.put("id","1");
map.put("name","lcc");
redisTemplate.opsForHash().putAll("key1",map);
redisTemplate.opsForHash().put("key1","age","24");
redisTemplate.opsForHash().putIfAbsent("key1","phone", "1326116");
boolean exist = redisTemplate.opsForHash().hasKey("key1", "age");
System.out.println("age key isExist:"+exist);
redisTemplate.opsForHash().increment("key1", "id",1);
printHash("id 加1","key1", "id");
redisTemplate.opsForHash().increment("key1", "id",1.2);
printHash("id 加1.2","key1", "id");
Set keys = redisTemplate.opsForHash().keys("key1");
System.out.println("keys:"+keys.toString());
List values = redisTemplate.opsForHash().values("key1");
System.out.println("values:"+values.toString());
Map entryes = redisTemplate.opsForHash().entries("key1");
}
public void printHash(String pre, String name, String key) {
String value = (String) redisTemplate.opsForHash().get(name,key);
System.out.println(pre + " " +"values:"+value);
}
结果:
age key isExist:true
id 加1 values:2
id 加1.2 values:3.2
keys:[id, name, age, phone]
values:[3.2, lcc, 24, 1326116]