redis 實戰教程、redis緩衝教程、redis訊息發布、訂閱、redis訊息佇列教程

來源:互聯網
上載者:User

標籤:

一:本教程使用環境: 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 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;
}

redis 實戰教程、redis緩衝教程、redis訊息發布、訂閱、redis訊息佇列教程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.