3.2 RedisとSpringの統合アプリケーション

8005 ワード

redisは日常の仕事で使いやすく、springと統合する必要があります.springフレームワークはRedisTemplateを提供しています.これは非常に良いコンポーネントで、Templateの設計モデルを採用しています.
Templateはspringフレームワークで非常に多く使われており、後のmqコンポーネント、mongodbコンポーネントはこれらのtemplateを使用します.
次に統合についてお話ししますが、比較的簡単です.
依存の追加

     org.springframework.data
      spring-data-redis
      1.7.2.RELEASE


      redis.clients
      jedis
      ${jedis.version}




この2つはspring統合に追加の依存性が必要で、1つはspring-data-redisで、1つはjedisクライアントで、残りはspring関連で、しばらく無視します.
構成アプリケーションを追加します.properties
redis.host=127.0.0.1
redis.port=6379
redis.pass=
redis.maxIdle=300
redis.testOnBorrow=true

これは前節と一致しており、デフォルトではhostとportの2つだけで十分です.
applicationContext-redis.xml Spring構成


    spring-data-redis  

    
    
    
    
        
        
        
    

    
        
    

    
        
    

redisConnectionFactoryこのセクションはredisを確立する接続語で、最大接続数、空き時間など、他のパラメータがあります.redis接続のチューニングが必要な場合は、これらのパラメータを調整する必要があります.RedisTemplate,StringRedisTemplateは2つのbeanであり、そのうち2番目は1番目を継承する.RedisTemplateのうちvalueのものはstringであってもよいし、他のオブジェクトであってもよいし、StringRedisTemplatevaluestringであってもよい.これは、多くのredisアプリケーションが単純なメモリ文字列であり、オブジェクトであればオブジェクトのシーケンス化や逆シーケンス化操作が必要であるためである.例を次に示します.
シーケンシャル化学器具類SerializeUtil
public class SerializeUtil {
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            //    
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static Object deserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            //     
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

シーケンス化されたツールクラスは多く、これは自分で書いたもので、原理は同じで、このクラスをストリームで2次制に読み出し、メモリに存在します.
RedisUtilツールクラス
@Component
public class RedisUtil {
   @Autowired
   private RedisTemplate redisTemplate;

   /**
    *   key    value
    * @param key
    * @param value
    */
   public void set(final String key, Object value) {
       final byte[] vbytes = SerializeUtil.serialize(value);
       redisTemplate.execute(new RedisCallback() {
           @Override
           public Object doInRedis(RedisConnection connection) throws DataAccessException {
               connection.set(redisTemplate.getStringSerializer().serialize(key), vbytes);
               return null;
           }
       });
   }

   /**
    *   key value,     ( )
    * @param key
    * @param value
    * @param l
    */
   public void set(final String key, Object value, final long l) {
       final byte[] vbytes = SerializeUtil.serialize(value);
       redisTemplate.execute(new RedisCallback() {
           @Override
           public Object doInRedis(RedisConnection connection) throws DataAccessException {
               connection.setEx(redisTemplate.getStringSerializer().serialize(key), l, vbytes);
               return null;
           }
       });
   }

   /**
    *   key   
    * @param key
    * @param elementType
    * @param 
    * @return
    */
   public  T get(final String key, Class elementType) {
       return redisTemplate.execute(new RedisCallback() {
           @Override
           public T doInRedis(RedisConnection connection) throws DataAccessException {
               byte[] keybytes = redisTemplate.getStringSerializer().serialize(key);
               if (connection.exists(keybytes)) {
                   byte[] valuebytes = connection.get(keybytes);
                   T value = (T) SerializeUtil.deserialize(valuebytes);
                   return value;
               }
               return null;
           }
       });
   }

   /**
    *   key    
    * @param key
    */
   public void del(final String key) {
       final byte[] keyBytes = redisTemplate.getStringSerializer().serialize(key);
       redisTemplate.execute(new RedisCallback() {
           @Override
           public Object doInRedis(RedisConnection connection) throws DataAccessException {
               connection.del(keyBytes);
               return null;
           }
       });
   }
}

これは直接使えるredisツールクラスで、設定、値取り、keyによる削除方法が含まれています.
テストの使用
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext-redis.xml"})
public class TestRedis {
    @Autowired
    private RedisUtil redisUtil;

    @Test
    public void testRedis() {
        redisUtil.set("name", "hello redis");//   
        System.out.println(redisUtil.get("name", String.class));//  key  
        redisUtil.del("name");//   
    }
}

ここではjunitでspringのプロファイルをロードし、RedisUtilを注入し、テストを行います.
StringRedisTemplate使用
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext-redis.xml"})
public class TestStringRedisTemplate {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void testRedis() {
        stringRedisTemplate.opsForValue().set("name", "hello stringRedisTemplate");//  
        System.out.println(stringRedisTemplate.opsForValue().get("name"));//  
        stringRedisTemplate.delete("name");//  
    }
}
StringRedisTemplateの使用は非常に簡単で、opsForValue()という方法でValueOperationsを取得し、値を設定して値を取るなどの操作を行う.
ソースのダウンロード
[本工事の詳細ソース](https://github.com/chykong/java_component/tree/master/chapter3_2_redis_spring)