redis integration springboot basic use

Redis can store the mapping between keys and 5 different types of data structures, these five types of data structures are String (String), List (list), the Set (set), the Hash (hash) and zset (orderly set)


String can be a string, integer or floating-point for the entire string or strings wherein part of performing the operation; and a floating point execution target increment (INCREMENT) or decrement (Decrement)

List a linked list, each node on the list contains a push or a pop-up element into the string ends from the list; list according to the offset trim (TRIM); Read a single or a plurality of elements; The value Find or remove elements

Set comprising a random string collector (unorderedcollection), and each string is contained it is unique, different Add, Get, remove the individual elements; check whether there is an element in a set; calculating intersection, union, difference; get to show off from the collection of random elements

Hash hash table contains unordered key-value pairs to add, get, remove a single key-value pairs; get all the key-value pairs

Zset mapping between ordered string member (Member) and floating-point score (Score), elements are added in the order determined by the size score, acquisition, delete a single element; according to the value range (range) or members Gets the element

Note: Java bean to serialize


1. Import dependence

//gradle

compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis', version: '2.1.3.RELEASE'


//pom

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-redis</artifactId>

    <version>2.1.3.RELEASE</version>

</dependency>

1

2

3

4

5

6

7

8

9

2. Configure redis

redis.config


@Configuration

public class RedisConfig {


    // used to solve the problem, then the sequence annotation operating redis

    @Bean(name = "myCacheManager")

    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {


        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

        RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();

        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair

                .fromSerializer (jsonSerializer);

        RedisCacheConfiguration defaultCacheConfig= RedisCacheConfiguration.defaultCacheConfig()

                .serializeValuesWith(pair);

        defaultCacheConfig.entryTtl(Duration.ofMinutes(30));

        return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);

    }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

    /**

 * Solve the problem with the sequence of operations redisTemplate

 *

 * @param factory RedisConnectionFactory

 * @return redisTemplate

 */

    @Bean

    @ConditionalOnMissingBean(name = "redisTemplate")

    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){

        // Configure redisTemplate

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(factory);

        // key serialization

        redisTemplate.setKeySerializer(STRING_SERIALIZER);

        // value serialization

        redisTemplate.setValueSerializer(JACKSON__SERIALIZER);

        // Hash key serialization

        redisTemplate.setHashKeySerializer(STRING_SERIALIZER);

        // Hash value serialization

        redisTemplate.setHashValueSerializer(JACKSON__SERIALIZER);

        redisTemplate.afterPropertiesSet();

        return redisTemplate;

    }


}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

Startup class configuration


@EnableCaching // cache operation allows annotation

@SpringBootApplication

public class ShoppingMallApplication {

   public static void main(String[] args) {

      SpringApplication.run(ShoppingMallApplication.class, args);

   }

}

1

2

3

4

5

6

7

application.yml arrangement


#redis cache configuration

repeat:

  database: 0

  host: @ip

  port: 6379

  timeout: 8000

  # If there is no time to write

  password:

  jedis:

    pool:

      # Connection pool maximum number of connections

      max-active: 10

      # Connection pool maximum blockage time

      max-wait: -1

      # The minimum connection pool idle connections

      min-idle: 0

      # Maximum connection pool idle connections

      max-idle: 8

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

3. Cache comment introduction

The operation result of the method cache, later to the same data, access cacheNames and key directly from the cache must fill in, if you do not fill the key, default key is the current method name, because different methods were updated when updating the cache failure

value: Specifies the name cache can specify a plurality (array)

key: key cache data used for the default method parameters support spEL

keyGenerator: key generator

CacheManager: Specifies the cache manager, or to obtain a parser, both second election

condition: the condition specified cache

unless: Negative unless cache when the condition is true, the return value will not be cached, judgment results may be acquired.

sync: whether asynchronous are not supported unless


@Cacheable(cacheNames = "xxx", key = "xxx")

1

Both methods are invoked to update a data cache modify the database while updating the cache, first call the target method will target methods cached, to the attention of updates, and the key to query the same time, otherwise the cache is not updated, property and @Cacheable the same


@CachePut(cacheNames = "xxx", key = "xxx")

1

Delete Cache

allEntries: Delete all the cached fields

beforeInvocation: whether before the method


@CacheEvict(cacheNames = "xxx", key = "xxx")

1

@CacheConfig

You can specify the public key generation strategy

Public cacheNames (value) can be written in a unified class above do not cover every cache on a name yet

Public CacheManager


@CacheConfig(cacheNames = "product")

public class ProductInfoController {

  

    @Caching(cacheable = {@Cacheable}, put = {@CachePut})

    public Response<Map<String, Object>> buyProduct(){

          //tO do sthing

    }

}

1

2

3

4

5

6

7

8

Key may be set to a dynamic parameter method (support EL)


@Cacheable(cacheNames = "xxx", key = "#openid")

public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid){

      //to do sthing

}

1

2

3

4

Composite comment

Go to update data into the cache when the query data //

Zhengzhou infertility hospital: http: //www.zzchyy110.com/

@Caching(cacheable = {@Cacheable}, put = {@CachePut})

@Caching(cacheable = {@Cacheable}, put = {@CachePut}, evict = {@CacheEvict})

1

2

4. Test

Notes version:


@CacheConfig (cacheNames = "shopping-productInfo") // custom name

public class ProductInfoController {   

    // simple usage 

    @Caching(cacheable = {@Cacheable}, put = {@CachePut})

    public Response<Map<String, Object>> getAllInfoById(@ApiParam("商品id") @RequestParam Integer id) {

        //to do sthing

    }

}

1

2

3

4

5

6

7

8

Redistemplate版:


@Autowired

private RedisTemplate redisTemplate;


 @Test 

public void demo(){


    // redis common type of data manipulation set zset not listed

        

    // string data type

    redisTemplate.opsForValue().set("test","123");

    redisTemplate.opsForValue (). get ( "test") // output is 123

    

   // list of data types

   . RedisTemplate.opsForList () rightPushAll ( "list", new String [] { "1", "2", "3"}); // insert elements from the right

   . RedisTemplate.opsForList () range ( "list", 0, -1); // get all elements

   . RedisTemplate.opsForList () index ( "listRight", 1); // Get element subscript 2

   . RedisTemplate.opsForList () rightPush ( "listRiht", "1"); // also be inserted from the right side from the left interpolated

   redisTemplate.opsForList () leftPop ( "list");. // pop elements from the left pop elements will not exist


   //hash

   redisTemplate.opsForHash () hasKey ( "redisHash", "111");. // determines whether there is the hash key

   redisTemplate.opsForHash () put ( "redisHash", "name", "111");. // store hash data

   . RedisTemplate.opsForHash () keys ( "redisHash"); // Get the hash value of the key corresponding to

   redisTemplate.opsForHash () get ( "redisHash", "age");. // obtain the hash value for a given key

 


Guess you like

Origin blog.51cto.com/14510351/2483959