Springboot Development (11)--Integration of Redis in Springboot

Source: Internet
Author: User
Tags assert object serialization redis serialization

dear friends, long time no see. Has not been updated recently, because the company's project has been catching progress, but also table structure replacement, and refactoring, but also iterative requirements. Feel the project is going to be rotten ... So a company's good or bad really and leaders have a great relationship, many programmers are really just three years programmer, Xie three years of code to transfer management, and finally lead to a limited level of technology, management levels can not keep up. Okay, I'll cut the crap and start the content this time, let's talk about the use of NoSQL database Redis in Springboot. integration of Redis in spring boot

maven dependencies introduced:

Redis is a memory-based, log-type, persistent, cached database that is saved in the form of a key-value format. It is not clear that a small partner can learn first, Redis in the current development is very common OH.

First, we first introduce dependencies in Maven:

<!--Redis Reliance-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

We then write the related configuration of Redis to Yml, where it is recommended to write different configurations according to the previous environment, Redis the port used by default is 6379, usually redis default to use the No. 0 database, the default total of 16 databases:

#redis配置
  Redis:
#  Database index
    database:0
#    server address
    host:127.0.0.1
#    Server connection Port
    port:6379
#    link password
    password:
#    Pool
    of Links:
#    Maximum number of connections (negative indicates no limit)
      Max-active:8
#      Maximum blocking wait time (negative indicates no limit)
      max-wait:1
#      max free link
      max-idle:8
#      Min Free link
      min-idle:0
#    Link timeout (ms)
    timeout:0

At this point, we have completed all the configuration of Redis, we can use it directly, we write a test case to test:

@SpringBootTest
@RunWith (springjunit4classrunner.class) public
class Redisautotest {

    @Autowired
    private stringredistemplate stringredistemplate;

    @Test public
    Void Save () {

        stringredistemplate.opsforvalue (). Set ("Zzp", "Big Z");
        Assert.assertequals ("Big Z", Stringredistemplate.opsforvalue (). Get ("Zzp"));
    }


OK, no problem, the same we use RDM open to see if the successful deposit.

OK, and there is no problem.
The stringredistemplate we use in this test case, because we said before that Redis uses Key-value format to save the data, which actually saves the

public class UserInfo implements serializable{private static final long serialversionuid = 1L;

    Private String Tel;

    Private String nickname;

    @Max (value = 999999,message = "Over maximum value") @Min (value = 000000,message = "Incorrect password set") Private String PassWord; Public UserInfo () {} @Override public String toString () {return "userinfo{" + "tel=
                ' + Tel + ' \ ' + ', nickname= ' + nickname + ' + ' + ', password= ' + PassWord + ' \ ' +
    '}';
        Public UserInfo (String tel, string nickname, String passWord) {This.tel = tel;
        This.nickname = nickname;
    This.password = PassWord;
    Public String Gettel () {return Tel;
    public void Settel (String tel) {This.tel = tel;
    Public String Getnickname () {return nickname;
    } public void Setnickname (String nickname) {this.nickname = nickname; } pUblic String GetPassword () {return passWord;
    } public void SetPassword (String passWord) {This.password = PassWord; }
}

Then we drive down to serialize the interface:

public class Redisobjectserializer implements redisserializer<object> {private converter<object,byte[]>
    Serializer = new Serializingconverter ();

    Private converter<byte[],object> Deserializer = new Deserializingconverter ();


    Static final byte[] Empty_array = new Byte[0];  @Override public byte[] Serialize (Object O) throws SerializationException {if (o = = null) {return
        Empty_array;
        try {return Serializer.convert (o);
        }catch (Exception e) {return empty_array; @Override public Object Deserialize (byte[] bytes) throws SerializationException {if IsEmpty (byte
        s)) {return null;
        try {return Deserializer.convert (bytes);
        }catch (Exception e) {throw new SerializationException ("Can not Deserializer", e); } Private Boolean IsEmpty (byte[] data) {return (data = NULL | | Data.length = = 0); }
}

We then reconfigure the redistemplate to use our own serialization object:

@Configuration public
class Redisconfig {

    @Bean
    jedisconnectionfactory jedisconnectionfactory () {
        return  new Jedisconnectionfactory ();
    }

    /**
     * Deposit Object serialization Information
     * @return * *
     @Bean public
    redistemplate<string,userinfo> Redisserizlizerobj () {
        redistemplate<string,userinfo> redistemplate = new redistemplate<string, Userinfo> ();
        Redistemplate.setconnectionfactory (Jedisconnectionfactory ());
        Redistemplate.setkeyserializer (New Stringredisserializer ());
        Redistemplate.setvalueserializer (New Redisobjectserializer ());
        Return redistemplate
    }
}

After we finish this work, we can continue to write test cases to verify our related configuration.

@Autowired
 private redistemplate<string,userinfo> Template;

 @Test public
 void Testobjserializer () throws interruptedexception {
        UserInfo user = new UserInfo ("111111", "snow "," 112358 ");
        Template.opsforvalue (). Set ("User:snow", User);
        Assert.assertequals (True,redistemplate.haskey ("User:snow"));
    }

The test results are all right and we can also see the serialized object we are depositing through RDM:

However, it is too troublesome to write a redistemplate for each object, in fact, we will deposit the object's ToString method in our development. So I'll put the code page into the object ToString method to everyone, you can according to their own needs to use:

    /**
     * The information after the object ToString
     * @return * * *
    @Bean public
   redistemplate<string,string> Redistemplate () {
        redistemplate<string,string> redistemplate = new Stringredistemplate ();
        Redistemplate.setconnectionfactory (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.setvalueserializer (Jackson2jsonredisserializer);
        Redistemplate.afterpropertiesset ();
        return redistemplate;
    }

Also validated by test cases can be found, you can use:

    @Test public
    void Testobj () throws interruptedexception {
        UserInfo user = new UserInfo ("15201803745", "Snow", " 112358 ");
        valueoperations<string,userinfo> operations = Redistemplate.opsforvalue ();
        Operations.set ("User:zzp", User);
        Thread.Sleep (1000);
        Operations.set ("User:zzq", User);
        Thread.Sleep (1000);
        Assert.assertequals (True,redistemplate.haskey ("User:zzp"));
        Assert.assertequals (True,redistemplate.haskey ("User:zzq"));
    }

The use of Redis in fact far more than these, including things can be handled through Redis. In general development, we will use Jedis to Redis operation, but because this time introduced Redis in Springboot integration, so no more words, if there is want to know the small partner can tell me, I am talking about how to use the Jedis operation. all of the above code I've uploaded to GitHub Round1-springboot If impatient partners can also go to clone I have completed the project, the project has some common features are written, and all write comments ... I also hope that you can help me to order a praise Oh ~ ~ ~ myspringboot

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.