一:本教程使用环境: ubuntu12.x 、jdk1.7 、Intellij idea、spring3.2.8 、redis服务端3.0,jedis客户端2.7.3
spring-data-redis 1.6.0
二:redis 服务端安装教程 这里不详解
三:redis 缓存特性 示例如下:
spring配置:
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="200"/>
<property name="maxIdle" value="10"/>
<property name="maxWaitMillis" value="3000"/>
<property name="minIdle" value="1"/>
<property name="testOnBorrow" value="true"/>
</bean>
<bean id="jedisFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="port" value="6379"/>
<property name="hostName" value="10.3.11.147"/>
<property name="poolConfig">
<ref bean="jedisPoolConfig"/>
</property>
<property name="timeout" value="10000"/>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisFactory"/>
<!--如果不配置Serializer,那么存储的时候智能使用String,如果用User类型存储,那么会提示错误User can't cast to String!!!-->
<!--<property name="keySerializer">-->
<!--<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>-->
<!--</property>-->
<!--<property name="valueSerializer">-->
<!--<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>-->
<!--</property>-->
</bean>
缓存使用测试类:
public class TestSringDataJedis {
static RedisTemplate redisTemplate;
public void set(String key,Object value){
//ValueOperations 理解成Map<Object,Object>
// redisTemplate.opsForValue().set("redis-key","I'm test spring-data-redis");
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set(key,value);
//BoundValueOperations的理解对保存的值做一些细微的操作
// BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(key);
}
public Object get(String key){
return redisTemplate.opsForValue().get(key);
}
public void setList(String key ,List<?> value){
//ListOperations可以理解为List<Object>
ListOperations listOperations= redisTemplate.opsForList();
listOperations.leftPush(key, value);
// .leftPushAll(value);
}
public Object getList(String key){
//ListOperations可以理解为List<Object>
return redisTemplate.opsForList().leftPop("test-list");
}
public void setSet(String key ,Set<?> value){
SetOperations setOperations= redisTemplate.opsForSet();
setOperations.add(key, value);
}
public Object getSet(String key){
return redisTemplate.opsForSet().members(key);
}
public void setHash(String key ,Map<String,?> value){
HashOperations hashOperations = redisTemplate.opsForHash();
hashOperations.putAll(key,value);
}
public Object getHash(String key){
return redisTemplate.opsForHash().entries(key);
}
public void delete(String key){
redisTemplate.delete(key);
}
// public void clearAll(){
// redisTemplate.multi();
// }
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("redis.xml");
redisTemplate = (RedisTemplate)ctx.getBean("redisTemplate");
TestSringDataJedis jedis = new TestSringDataJedis();
//String
jedis.set("test-string", "good-中国抗战胜利");
System.out.println("test-string = " + jedis.get("test-string"));
//POJO
User user =new User();
user.setName("邓洋");
user.setBirthday(new Date());
user.setSex(true);
jedis.set("test-user", user);
System.out.println("test-user = " + jedis.get("test-user"));
System.out.println("test-user:name = " + ((User)jedis.get("test-user")).getName());
//List
List<String> list = new ArrayList<String>();
list.add("张三");
list.add("李四");
list.add("麻子");
String key_list = "test-list";
jedis.setList(key_list, list);
List<String> test_list = (List<String>)jedis.getList(key_list);
for (int i = 0; i < test_list.size(); i++) {
System.out.println(i + " = " + test_list.get(i));
}
//Map
String key_map = "test-map";
Map<String,Object> map = new HashMap<String, Object>();
map.put("map1","map-张三");
map.put("map2","map-李四");
map.put("map3", "map-麻子");
jedis.setHash(key_map, map);
Map<String,Object> getMap = (Map<String,Object>)jedis.getHash(key_map);
return;
}
}
四:消息订阅和发布
spring配置:
<bean id="listener" class="com.dengyang.redis.TestMessage"/>
<redis:listener-container connection-factory="jedisFactory">
<!-- the method attribute can be skipped as the default method name is "handleMessage" -->
<!-- topic代表监听的频道,是一个正规匹配 其实就是你要订阅的频道-->
<redis:listener ref="listener" method="handleMessage" topic="*"/>
</redis:listener-container>
消息发布:
/**
* 发布频道消息
* @param pkey
* @param message
* @return 返回订阅者数量
*/
redisTemplate.convertAndSend("java", "java我发布的消息!");
public class TestMessage {
static RedisTemplate redisTemplate;
public static void main(String[] args) {
new ClassPathXmlApplicationContext("/redis.xml");
while (true){
System.out.println("current time: " + new Date());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void handleMessage(Serializable message) {
if (message == null) {
System.out.println("null");
} else if (message.getClass().isArray()) {
System.out.println(Arrays.toString((Object[]) message));
} else if (message instanceof List<?>) {
System.out.println(message);
} else if (message instanceof Map<?, ?>) {
System.out.println(message);
} else {
System.out.println(message);
}
}
}
五:消息队列的使用
private RedisTemplate redisTemplate;
//入队key 是消息频道 ,value 消息内容
public Long putToQueue(final String key, final String value) {
Long l = (Long) this.getRedisTemplate().execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection)
throws DataAccessException {
// TODO Auto-generated method stub
return connection.lPush(key.getBytes(), value.getBytes());
}
});
return l;
}
//读取消息 (读过队列中消息就没有了)key 是消息频道
public String getFromQueue(final String key) {
// TODO Auto-generated method stub
byte[] b = (byte[]) this.getRedisTemplate().execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection)
throws DataAccessException {
// TODO Auto-generated method stub
return connection.lPop(key.getBytes());
}
});
if(b != null)
{
return new String(b);
}
return null;
}