1. 程式人生 > >14-SpringBoot之Redis(一)——單機Redis

14-SpringBoot之Redis(一)——單機Redis

SpringBoot之Redis(一)——單機Redis

1. 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">
<modelVersion>4.0.0</modelVersion> <groupId>com.springboot</groupId> <artifactId
>
redis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>redis</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId
>
<artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </exclusion> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

2. application.yml

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:
    jedis:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 8
        min-idle: 0
    timeout: 2000ms

3. Redis序列化配置類

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig  extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory ) {
        //設定序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer); // key序列化
        redisTemplate.setValueSerializer(stringSerializer); // value序列化
        redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
        redisTemplate.setHashValueSerializer(stringSerializer); // Hash value序列化
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

4. 案例演示

4.1 redis操作字串

/***
 * redis操作字串
 */
@RequestMapping("/testString")
public void  testString() {
    redisTemplate.opsForValue().set("mykey1", "v1");

    redisTemplate.opsForValue().set("int_key", "1");
    redisTemplate.opsForValue().set("int_key1", "4");

    //運算,+1
    redisTemplate.opsForValue().increment("int_key",1);
    //運算,-1
    redisTemplate.opsForValue().decrement("int_key1", 1);

    //獲取值
    String v1 = redisTemplate.opsForValue().get("mykey1").toString();
    System.out.println(v1);

}

4.2 redis操作雜湊資料

/***
* redis操作雜湊資料
* @return
*/
@RequestMapping("/testHash")
public void testHash() {
   Map<String, String> map =new HashMap<String, String>();
   map.put("f1","v1");
   map.put("f2","v2");
   map.put("f3","v3");
   //存入一個雜湊
   redisTemplate.opsForHash().putAll("map",map);
   redisTemplate.opsForHash().put("map","f0","v0");
   //繫結雜湊
   BoundHashOperations hashOperations = redisTemplate.boundHashOps("map");
   boolean hasKey = hashOperations.hasKey("f1");
   String v1= hashOperations.get("f1").toString();
   //新增一個欄位
   hashOperations.put("f4","v4");
   //刪除一/多個欄位
   hashOperations.delete("f2","f3");

}

4.3 redis操作連結串列

/***
 * redis操作連結串列
 */
@RequestMapping("/testList")
public void testList() {

    //插入兩個連結串列
    //l1:從左至右為v10,v8,v6,v4,v2
    redisTemplate.opsForList().leftPushAll("l1","v2","v4","v6","v8","v10");

    //l2:從左至右為v1,v3,v5,v7,v9
    redisTemplate.opsForList().rightPushAll("l2","v1","v3","v5","v7","v9");

    //繫結l2
    BoundListOperations boundListOperations = redisTemplate.boundListOps("l2");
    //從右邊彈出一個成員
    Object r1 = boundListOperations.rightPop();
    //按索引取,索引從0開始,此處r2值為v3
    Object r2 = boundListOperations.index(1);
    //從左邊插入一個
    boundListOperations.leftPush("v0");

    //連結串列長度
    Long size = boundListOperations.size();

    //取連結串列區間值
    List eLs = boundListOperations.range(1,size-2);

}

4.4 redis操作集合

/***
 * redis操作集合
 */
@RequestMapping("/testSet")
public void testSet() {
    //插入兩個集合
    //s1:v1重複
    redisTemplate.opsForSet().add("s1","v1","v1","v3","v5","v7","v9");
    redisTemplate.opsForSet().add("s2","v1","v2","v3","v4","v5");
    //繫結s2
    BoundSetOperations boundSetOperations = redisTemplate.boundSetOps("s2");
    boundSetOperations.add("v6","v7");
    boundSetOperations.remove("v1","v2");

    Set s1 = boundSetOperations.members();

    //求交集
    Set inter = boundSetOperations.intersect("s1");
    boundSetOperations.intersectAndStore("s1","inter");

    //求差集
    boundSetOperations.diffAndStore("s1","diff");

    //求並集
    boundSetOperations.unionAndStore("s1","union");

}

4.5 redis操作有序集合

/***
 * redis操作有序集合
 */
@RequestMapping("/testZSet")
public void testZSet() {
    Set<ZSetOperations.TypedTuple<String>> typedTupleSet = new HashSet<>();
    for(int i=1;i<=9;i++){
        double score = i*0.1;
        ZSetOperations.TypedTuple<String> typedTuple
                = new DefaultTypedTuple<String>( "value" + i , score) ;
        typedTupleSet.add(typedTuple);
    }

    //往有序集合插入元素
    redisTemplate.opsForZSet() .add ("zset1", typedTupleSet );
    //繫結 zset1 有序集合操作
    BoundZSetOperations<String, String> zsetOps
            = redisTemplate . boundZSetOps ( "zset1");

    zsetOps.add ("",0.26 );
    Set<String> setRange = zsetOps.range (1 , 6 );
    //按分數排序獲取有序集合
    Set<String> setScore = zsetOps .rangeByScore(0.2 , 0.6);
    Range range =new Range() ;
    //大於value3
    range.gt("value3");
    //大於等於value3
    //range.gte("value3");
    //小於value3
    // range.lt("value3");
    //小於等於value8
    range.lte ("value8");
    Set<String> setLex = zsetOps.rangeByLex(range);
    //刪除元素
    zsetOps.remove ("value9" , "value2");
    //求分數
    Double score= zsetOps.score ( "value8");

    //在下標區間下,按分數排序,同時返回value和score
    Set<ZSetOperations.TypedTuple<String>> rangeSet = zsetOps.rangeWithScores(1 , 6) ;
    //在分數區間下,按分數排序,同時返回value和score
    Set<ZSetOperations.TypedTuple<String>>scoreSet = zsetOps.rangeByScoreWithScores(1, 6);
    //按從大到小排序
    Set<String> reverseSet = zsetOps.reverseRange(2,8);

}

5. 原始碼下載

原始碼下載地址:https://download.csdn.net/download/huangjun0210/10797230