spring.redis.host=192.168.150.99
spring.redis.port=6379
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
@Configuration
public class MyTemplate {
@Bean
public StringRedisTemplate ooxx(RedisConnectionFactory fc){
StringRedisTemplate tp = new StringRedisTemplate(fc);
tp.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
return tp ;
}
}
public class TestRedis {
@Autowired
RedisTemplate redisTemplate;
@Autowired
@Qualifier("ooxx")
StringRedisTemplate stringRedisTemplate;
@Autowired
ObjectMapper objectMapper;
public void testRedis(){
RedisConnection conn = redisTemplate.getConnectionFactory().getConnection();
conn.set("hello02".getBytes(),"水电费稍等".getBytes());
System.out.println(new String(conn.get("hello02".getBytes())));
Person p = new Person();
p.setName("zhangsan");
p.setAge(16);
Jackson2HashMapper jm = new Jackson2HashMapper(objectMapper, false);
stringRedisTemplate.opsForHash().putAll("sean01",jm.toHash(p));
Map map = stringRedisTemplate.opsForHash().entries("sean01");
Person per = objectMapper.convertValue(map, Person.class);
System.out.println(per.getName());
stringRedisTemplate.convertAndSend("ooxx","hello");
RedisConnection cc = stringRedisTemplate.getConnectionFactory().getConnection();
cc.subscribe(new MessageListener() {
@Override
public void onMessage(Message message, byte[] pattern) {
byte[] body = message.getBody();
System.out.println(new String(body));
}
}, "ooxx".getBytes());
while(true){
stringRedisTemplate.convertAndSend("ooxx","hello from wo zi ji ");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}