1. 程式人生 > >SpringDataRedis操作Redis簡單案例

SpringDataRedis操作Redis簡單案例

jedis 4.2 圖片 code throw .get ngs cto opera

Jedis

  Jedis是Redis官方推出的一款面向Java的客戶端,提供了很多接口供Java語言調用。可以在Redis官網下載,當然還有一些開源愛好者提供的客戶端,如Jredis、SRP等等,推薦使用Jedis。

Spring Data Redis

  spring-data-redis是spring大家族的一部分,提供了在srping應用中通過簡單的配置訪問redis服務,對reids底層開發包(Jedis, JRedis, and RJC)進行了高度封裝,RedisTemplate提供了redis各種操作、異常處理及序列化,支持發布訂閱,並對spring 3.1 cache進行了實現。

? spring-data-redis針對jedis提供了如下功能:

  1. 連接池自動管理,提供了一個高度封裝的“RedisTemplate”類

  2. 針對jedis客戶端中大量api進行了歸類封裝,將同一類型操作封裝為operation接口

    • ValueOperations:簡單K-V操作

    • SetOperations:set類型數據操作

    • ZSetOperations:zset類型數據操作

    • HashOperations:針對map類型的數據操作

    • ListOperations:針對list類型的數據操作

簡單案例:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId
>pyg_demo</artifactId> <groupId>cn.itcast.demo</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>spring_data_redis_demo</artifactId> <!-- 集中定義依賴版本號 --> <properties> <spring.version>4.2.4.RELEASE</spring.version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> </dependency> <!-- redis做緩存 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.7.2.RELEASE</version> </dependency> </dependencies> <build> <plugins> <!-- java編譯插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>

resources文件:

技術分享圖片

redis-config.properties

# Redis settings 
# 服務器 IP
redis.host=192.168.44.32
# 端口
redis.port=6379
# 密碼
redis.pass=
# 使用的dbIndex
redis.database=0
# 最大空閑數
redis.maxIdle=300
# 連接時的最大等待毫秒數
redis.maxWait=3000
# 在提取一個jedis實例時,是否提前進行驗證操作;如果為true,則得到的jedis實例均是可用的;
redis.testOnBorrow=true

applicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans   
            http://www.springframework.org/schema/beans/spring-beans.xsd   
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context.xsd">  
  
   <context:property-placeholder location="classpath*:properties/*.properties" />   
  
   <!-- redis 相關配置 --> 
   <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
     <property name="maxIdle" value="${redis.maxIdle}" />   
     <property name="maxWaitMillis" value="${redis.maxWait}" />  
     <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
   </bean>  
  
   <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 
       p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>  
   
   <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
        <property name="connectionFactory" ref="JedisConnectionFactory" />  
   </bean>  
      
</beans>  

測試:

/**
* 值類型操作
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestValue {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void setValue() throws Exception {
        redisTemplate.boundValueOps("value1").set("李四");
    }

    @Test
    public void getValue() throws Exception {
        String name = (String) redisTemplate.boundValueOps("value1").get();
        System.out.println(name);
    }

    @Test
    public void delete() throws Exception {
        redisTemplate.delete("value1");
    }
}
/**
* set類型操作
*@Param
*@return
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestSet {
    @Autowired
    private RedisTemplate redisTemplate;
    //set1:[‘‘,‘‘]
    @Test
    public void setValue() throws Exception {
        redisTemplate.boundSetOps("set1").add("劉備");
        redisTemplate.boundSetOps("set1").add("曹操");
        redisTemplate.boundSetOps("set1").add("孫權");
    }

    @Test
    public void getValue() throws Exception {
        Set set = redisTemplate.boundSetOps("set1").members();
        System.out.println(set);
    }

    @Test
    public void remove() throws Exception {
        redisTemplate.boundSetOps("set1").remove("曹操");
    }

    @Test
    public void delete() throws Exception {
        redisTemplate.delete("set1");
    }
}
/**
* list類型操作
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestList {
    @Autowired
    private RedisTemplate redisTemplate;

    // list1 : []

    @Test
    public void setValue1() throws Exception {
        redisTemplate.boundListOps("list1").leftPush("唐僧");
        redisTemplate.boundListOps("list1").leftPush("悟空");
        redisTemplate.boundListOps("list1").leftPush("八戒");
        redisTemplate.boundListOps("list1").leftPush("沙僧");
    }

    @Test
    public void getValue1() throws Exception {
        List list = redisTemplate.boundListOps("list1").range(0, 10);
        System.out.println(list);
    }

    @Test
    public void setValue2() throws Exception {
        redisTemplate.boundListOps("list2").rightPush("大喬");
        redisTemplate.boundListOps("list2").rightPush("小喬");
        redisTemplate.boundListOps("list2").rightPush("孫尚香");
    }

    @Test
    public void getValue2() throws Exception {
        List list = redisTemplate.boundListOps("list2").range(0, 10);
        System.out.println(list);
    }

    @Test
    public void getByIndex() throws Exception {
        String name = (String) redisTemplate.boundListOps("list1").index(1);
        System.out.println(name);
    }

    @Test
    public void remove() throws Exception {
        redisTemplate.boundListOps("list1").remove(2,"八戒");
    }


}
/**
* hash類型操作
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestHash {
    @Autowired
    private RedisTemplate redisTemplate;
    //specList:{key:value}

    @Test
    public void setValue() throws Exception {
        redisTemplate.boundHashOps("map1").put("a","劉備");
        redisTemplate.boundHashOps("map1").put("b","關羽");
        redisTemplate.boundHashOps("map1").put("c","張飛");
    }

    @Test
    public void getKeys() throws Exception {
        Set set = redisTemplate.boundHashOps("map1").keys();
        System.out.println(set);
    }

    @Test
    public void getValues() throws Exception {
        List list = redisTemplate.boundHashOps("map1").values();
        System.out.println(list);
    }

    @Test
    public void getValue() throws Exception {
        String name = (String) redisTemplate.boundHashOps("map1").get("b");
        System.out.println(name);
    }

    @Test
    public void remove() throws Exception {
        redisTemplate.boundHashOps("map1").delete("c");
    }

    @Test
    public void delete() throws Exception {
        redisTemplate.delete("map1");
    }
}

SpringDataRedis操作Redis簡單案例