redis 實戰教程、redis緩存教程、redis消息發佈、訂閱、redis消息隊列教程

一:本教程使用環境: ubuntu12.x 、jdk1.7 、Intellij idea、spring3.2.8 、redis服務端3.0,jedis客戶端2.7.3 java

spring-data-redis 1.6.0 redis

二:redis 服務端安裝教程 這裏不詳解 spring

三:redis 緩存特性 示例以下: ubuntu

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> ide


緩存使用測試類: 測試

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;
    }
} this

四:消息訂閱和發佈 idea

spring配置: spa

<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 Long publish(final String channel,final String message) {
// TODO Auto-generated method stub
Long recvs = (Long)this.getRedisTemplate().execute(new RedisCallback<Object>() {


public Object doInRedis(RedisConnection connection)
throws DataAccessException {
// TODO Auto-generated method stub
return connection.publish(channel.getBytes(), message.getBytes());
}
});
return recvs;
}

消息處理類:

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; }

相關文章
相關標籤/搜索