IntelliJ idea to build the Spring Boot Project (iii) Configure transactions and Redis caching

Source: Internet
Author: User
Tags redis install redis
IntelliJ Idea builds the spring boot project –> configuration transaction and Redis cache

tags (space-delimited): springboot Java background First , start configuration things

Similar to our previous configuration Spring-dao, we can see that configuring things in the SSM is configured as follows

    This doesn't have to be configured  , because when we @configuration, it's all  package scanned  
 <!--scan service packages for all types of annotations used-->
    < Context:component-scan base-package= "Com.ruolan.o2o.service"/>

    <!--configuration transaction manager--> <bean id=
    " TransactionManager "
        class=" Org.springframework.jdbc.datasource.DataSourceTransactionManager ">
        < !--Inject database connection pool-->
        <property name= "DataSource" ref= "DataSource"/>
    </bean>

    <!-- Configure declarative transaction-->
    <tx:annotation-driven transaction-manager= "TransactionManager"/>

So we need to create a transactionmanagementconfiguration class

@Configuration
//First Use annotation @enabletransactionmanagement to open transaction support
//Add @transactional to service method
@ Enabletransactionmanagement public
class Transactionmanagementconfiguration implements transactionmanagementconfigurer {

    @Autowired
    //inject datasourceconfiguration inside datasource Get
    private DataSource DataSource through CreateDataSource;

    /**
     * About transaction management  need to return platformtransactionmanager
     *
     * @return Platformtransactionmanager * *
    @Override public
    Platformtransactionmanager Annotationdriventransactionmanager () {return
        new Datasourcetransactionmanager (DataSource);
    }
Second, configure the Redis cache

Our next two classes are related to the Redis Cache tool class Jedispoolwriper Jedisutil

Add the following related configuration for Redis in the Application.peoperties file

#redis缓存的相关配置
#host
redis.hostname=127.0.0.1
#redis端口号  default 6379
redis.port=6379
Redis.database=0
redis.pool.maxactive=600
redis.pool.maxidle=300
redis.pool.maxwait=3000
Redis.pool.testonborrow=true

Similar to the creation of a data connection pool, create a Redisconfiguration configuration class

@Configuration public class Redisconfiguration {@Value ("${redis.hostname}") private String hostname;

    @Value ("${redis.port}") private int port;

    @Value ("${redis.database}") private int database;

    @Value ("${redis.pool.maxactive}") private int maxactive;

    @Value ("${redis.pool.maxidle}") private int maxidle;

    @Value ("${redis.pool.maxwait}") Private long maxwait;

    @Value ("${redis.pool.testonborrow}") Private Boolean testonborrow;

    @Autowired private Jedispoolconfig Jedispoolconfig;

    @Autowired private Jedispoolwriper Jedispoolwriper;

    @Autowired private Jedisutil Jedisutil; @Bean (name = "Jedispoolconfig") public jedispoolconfig Createjedispoolconfig () {jedispoolconfig jedispoolconf
        IG = new Jedispoolconfig ();
        Control how many Jedis instances of a pool can be allocated jedispoolconfig.setmaxtotal (maxactive); The maximum number of idle maxidle connections in the connection pool here is a value of 20//indicates that even if there is no database connection, you can still maintain 20 idle connections without being purged and ready to be on standby JEDispoolconfig.setmaxidle (Maxidle);
        Maximum latency: The maximum time (in milliseconds) that the connection pool waits for a connection to be returned when there is no connection to use (the millisecond technique) throws an exception Jedispoolconfig.setmaxwaitmillis (maxwait);
        Check the validity jedispoolconfig.settestonborrow (testonborrow) when getting the connection;
    return jedispoolconfig; @Bean (name = "Jedispoolwriper") public jedispoolwriper Createjedispoolwriper () {Jedispoolwriper jedisp
        Oolwriper = new Jedispoolwriper (JEDISPOOLCONFIG, hostname, port);
    return jedispoolwriper; /** * Create Redis Tool class encapsulates redis connections for related operations * * @return/@Bean (name = "Jedisutil") public Je
        Disutil Createjedisutil () {jedisutil jedisutil = new Jedisutil ();
        Jedisutil.setjedispool (Jedispoolwriper);
    return jedisutil; @Bean (name = "Jediskeys") public Jedisutil.keys Createjediskeys () {Jedisutil.keys Jediskeys = Jedisuti
        L.new Keys ();
    return Jediskeys; @Bean (name = "Jedisstrings") public jedisutil.strings CREAtejedisstrings () {jedisutil.strings jedisstrings = jedisutil.new Strings ();
    return jedisstrings; @Bean (name = "jedislists") public jedisutil.lists createjedislists () {jedisutil.lists jedislists = Jed
        Isutil.new Lists ();
    return jedislists; @Bean (name = "Jedissets") public jedisutil.sets createjedissets () {jedisutil.sets jedissets = Jedisuti
        L.new Sets ();
    return jedissets; @Bean (name = "Jedishash") public Jedisutil.hash Createjedishash () {Jedisutil.hash Jedishash = Jedisuti
        L.new Hash ();
    return jedishash;
 }
}

The directory structure of the above two classes (transaction and Redis configuration classes) is shown in the following illustration:

We use the Redis cache in the service so the code is as follows:

 @Autowired private jedisutil.strings jedisstrings; Redis installation and configuration to run after this is possible is to go cache//https://www.jianshu.com/p/6b5eca8d908b @Autowired Private

    Jedisutil.keys Jediskeys;

    @Autowired private Areadao Areadao;

    private static String Arealistkey = "Arealist";
        @Override public list<area> getarealist () throws IOException {String key = Arealistkey;
        List<area> arealist = null;
        Objectmapper mapper = new Objectmapper ();
            To determine if there is a cache if (!jediskeys.exists (key) {//Not yo cache query Database arealist = Areadao.queryarea ();
            String jsonstring = mapper.writevalueasstring (arealist);
        Jedisstrings.set (key, jsonstring);
            else {//There is cache this time from the cache from the key to get the cached data and then converted to the data we need String jsonstring = Jedisstrings.get (key); Javatype Javatype = Mapper.gettypefactory (). Constructparametrictype (Arraylist.class,Area.class);
        Arealist = Mapper.readvalue (jsonstring, Javatype);
    return arealist;
 }
Test Service
The test class joins the following two annotations
@RunWith (springrunner.class)
@SpringBootTest public
class Areaservicetest {

    @ autowired
    private Areaservice areaservice;

    Redis installation and configuration      to run after the start of this is ok is to  go cache
    //    https://www.jianshu.com/p/6b5eca8d908b

    @Test Public
    void Testgetarealist () throws IOException {
        list<area> arealist = Areaservice.getarealist (); C15/>system.out.println ("The number of query area collections is:" + arealist.size ());
    }

Let's look at the results of the input:

third, the bug encountered

At first did not understand what Redis is, just feel is a cache, and did not expect to need a variety of configuration –> caused no redis–server, in the test will be reported
Could not get a resource the error from the pool, which works well after the Redis is configured and then run again after it is started. springboot test Project address https://github.com/wuyinlei/springtest https://github.com/wuyinlei/springtest https:/ /github.com/wuyinlei/springtest RELATED LINKS article install Redis in MAC environment

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.