Springboot Diary--redis Integration

Source: Internet
Author: User
Tags serialization

In the previous article, a simple record of how the cache is used, this article will integrate our familiar redis.

So how to integrate it? First need to download and install, for the convenience of use, you can also do environment variable configuration.

Download and install the method, before the introduction, in the use of Docker, here do not do the relevant introduction, you want to use in the Windows environment, self-search how to Windows installation using Redis Bar ~ (see here also can)

The point: springboot corresponding (bring) redisclient is different

springboot1.5.x version, Jedis
springboot2.x version-> lettuce (This article takes 2.x as an example)

Redis Startup and Application

Start the Redis service and open the management client. The default port number, which can be implemented by modifying CONFIG.

  Follow the steps to link local redis, if you are installing on a remote server, IP remembers filling in the server.

Check our link, right-click on Console or CTRL+T, open the console, let's test if the command is available ~

Enter the command in the console and take a look (Redis command click to view)

Continue to enter the command, you can see the string will be the corresponding stitching, which is the function of appending the key value of the command. Other orders, you can go to try ~

  

Integration into the Springboot

Next, we'll integrate this redis into Springboot, first of all, adding in Pom.xml

        < Dependency >            < groupId >org.springframework.boot</groupId>            <  Artifactid>spring-boot-starter-data-redis</artifactid>         </dependency>

1. Configure Redis: Add to the configuration file: (if it is a remote server, replace the IP yourself)

spring.redis.host=127.0.0.1

After adding it, let's test it, first of all, in order to access the data into Redis, add the following code, and we'll look at how these two are used.

    @Autowired    stringredistemplate stringredistemplate;     // k-v are all strings .     @Autowired    redistemplate redistemplate;     // k-v are all objects .

Look at the string, the same function as before in the console input command, after the test, check the next redis, there is indeed a generated MSG, indicating that our association and operation is successful.

        Stringredistemplate.opsforvalue (). Append ("msg", "Hello"); Append adds two strings, which is the K-V string operation above

So, you should understand the second k-v is the object of the meaning of it? In the continuation test method, write this: (the object that we are querying is stored in the cache)

        Employee Empbyid = Employeemapper.getempbyid (1);        Redistemplate.opsforvalue (). Set ("emp-01", Empbyid);

Look at the result: (cannot serialize means it can't be serialized, here's how to do it, and later why and how to optimize it)

We will bean. The class of employee is written so that the basic serialization can be guaranteed: implements Serializable

 Public class Implements Serializable {xxxx}

Run again to see the results: (running successfully, but this pile of garbled like what is it?) )

In fact, the default serialization is JDK, we need to optimize ourselves, such as the serialization of programming json.

To see how to optimize it, we need to create a Redis configuration ourselves to serialize the JSON format we want (in fact, the method in the Redisautoconfiguration is slightly modified)

Note that I put the @enablecaching in the main program here, the main program there is no need to write? We'll experiment with that later.

Importorg.springframework.cache.annotation.EnableCaching;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;Importorg.springframework.data.redis.cache.RedisCacheConfiguration;ImportOrg.springframework.data.redis.cache.RedisCacheManager;ImportOrg.springframework.data.redis.cache.RedisCacheWriter;Importorg.springframework.data.redis.connection.RedisConnectionFactory;ImportOrg.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;ImportOrg.springframework.data.redis.serializer.RedisSerializationContext;Importjava.time.Duration, @Configuration @enablecaching Public classMyredisconfig {@Bean PublicRediscachemanager Empcachemanager (redisconnectionfactory redisconnectionfactory) {RedisCacheConfiguration red Iscacheconfiguration=rediscacheconfiguration.defaultcacheconfig (). Entryttl (Duration.ofhours (1))//Set cache validity for one hour. Serializevalueswith (RedisSerializationContext.SerializationPair.fromSerializer ( NewGenericjackson2jsonredisserializer ()));//set JSON format serialization        returnRediscachemanager. Builder (Rediscachewriter.nonlockingrediscachewriter (redisconnectionfactory))    . Cachedefaults (Rediscacheconfiguration). build (); }}

Then, using our own template method, do a test to see the result: (the note proves that the wood is problematic)

        Employee Empbyid = Employeemapper.getempbyid (1);        Employeeredistemplate.opsforvalue (). Set ("emp-01", Empbyid);

  

Does it look much more comfortable?

Of course, if we do different writing for different situations is sometimes necessary, so we can also write: (New line, look at the change, you know ~), but remember, if you have more than one personality configuration to add the annotation @Primary, This allows the bean to be used as the default primary cache manager, or it will be an error.

@Bean PublicRediscachemanager Empcachemanager (redisconnectionfactory redisconnectionfactory) {RedisCacheConfiguration red Iscacheconfiguration=rediscacheconfiguration.defaultcacheconfig (). Entryttl (Duration.ofhours (1))//Set cache validity for one hour. Serializevalueswith (RedisSerializationContext.SerializationPair.fromSerializer ( NewJackson2jsonredisserializer<employee> (Employee.class)));//set JSON format serialization        returnRediscachemanager. Builder (Rediscachewriter.nonlockingrediscachewriter (redisconnectionfactory))    . Cachedefaults (Rediscacheconfiguration). build (); }

As above, the simple use of Redis said these, behind I may also extend the article, specifically how to use, please pay attention to ~

  

  

Springboot Diary--redis Integration

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.