Spring Boot implement caching mechanism from entry to the master (vi) integration Redis

Redis (Remote Dictionary Server), that is remote dictionary service, is an open source use written in ANSI C, support network, based on the persistence of memory can log type, Key-Value database, and provides multi-lingual API.

Redis is a key-value high-performance memory database, a data structure commonly referred to as the server, because the value may be a string, a hash, a list, a set of ordered set, and other types, the system is now in constant pursuit of high concurrency and high efficiency under the environment, Redis is widely used.

In a previous article, " the Spring the Boot from entry to the master (D) connect to the MySQL database (with source) " source project on the basis of article (attention "Java featured" micro-channel public number, switching to the background -> Aggregation -> Open Source project, you can view the Spring Boot series frame from entry to the master tutorial).

Database table data store by querying MySQL to Redis cache, then re-use Redis return parameter query data presented to the browser, using the Spring Boot Redis integration framework to implement caching mechanisms to share your reference and study.

  Maven project pom.xml file pom.xml configuration file the following information in Spring Boot project:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.M2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yoodb</groupId>
    <artifactId>springboot-study-demo04</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>springboot-study-demo04</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.xmlunit</groupId>
            <artifactId>xmlunit-core</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
        </resources>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

</project>

 

MySQL database data source class file

Create a class named DataSourceConfig, on an already detailed for the content here is not too much to explain, if you do not understand what can look at the previous record [micro-channel public number "Java selection", Spring Boot from entry Mastering series], the specific code as follows:

package com.yoodb.study.demo04.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.yoodb.study.demo04.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfig {
    @Bean(name = "dataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource getDateSourceOne() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory oneSqlSessionFactory(@Qualifier("dataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
        return bean.getObject();
    }
    
    @Bean("sqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlsessiontemplate(
            @Qualifier("sqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}

 

Redis cache class file

Create RedisConfig configuration class, specific code as follows:

package com.yoodb.study.demo04.datasource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean("redisTemplate")
    @ConfigurationProperties(prefix="spring.redis")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        //将key的序列化设置成StringRedisSerializer
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setHashKeySerializer(keySerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
  
}

 

 

Note: When adding RedisConfig configuration, because the connection redis need RedisConnection and RedisConnectionFactory, RedisConnection is created by RedisConnectionFactory.

  Entity class file

Add BootUser entity class files, specific code as follows:

package com.yoodb.study.demo04.bean;

import java.io.Serializable;

public class BootUser implements Serializable {
    private String id;
    private String name;
    private String detail;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }
}

 

新增mapper接口类文件

mapper interface class file, specific code as follows:

package com.yoodb.study.demo04.mapper;
import com.yoodb.study.demo04.bean.BootUser;
import java.util.List;
public interface BootUserMapper {
    List<BootUser> selectAll();
}

 

新增mapper xml文件

In src / main / resources / mapper / (add new file does not exist) to create a file BootUserMapper.xml specific configuration information is as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.yoodb.study.demo04.mapper.BootUserMapper" >
    <resultMap id="BaseResultMap" type="com.yoodb.study.demo04.bean.BootUser" >
        <id column="id" property="id" jdbcType="VARCHAR" />
        <result column="user_name" property="name" jdbcType="VARCHAR" />
        <result column="detail" property="detail" jdbcType="VARCHAR" />
    </resultMap>

    <select id="selectAll" resultMap="BaseResultMap">
    select
         id, user_name, detail
    from boot_user order by detail asc
    </select>
</mapper>

 

application.properties文件

Application.properties increase MySQL database connection configuration file cache and Redis connection configuration parameters, refer to the following information:

#MySQL
spring.datasource.jdbc-url=jdbc:mysql://123.57.47.154:3306/dba
spring.datasource.username=root
spring.datasource.password=wangyoodb
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

#Redis
#Redis数据库索引(默认为0)
spring.redis.database=0
#Redis服务器地址
spring.redis.host=127.0 . 0.1 
#Redis server port 
spring.redis.port = 6379

 

 

NOTE: spring.redis.database wherein the configuration parameters can usually 0, the Redis configuration when the number of databases may be provided, the default is 16, can be understood as the database schema.

  Create a service class file

New file name BootUserService class files, the specific code as follows:

package com.yoodb.study.demo04.service;

import java.util.List;

import com.yoodb.study.demo04.bean.BootUser;
import com.yoodb.study.demo04.mapper.BootUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class BootUserService {

    @Autowired
    private BootUserMapper bootUserMapper;

   @Autowired
    private RedisTemplate redisTemplate;

    public List<BootUser> getUsers(){
        List<BootUser> bootUsers = bootUserMapper.selectAll();
        redisTemplate.opsForValue().set("bootUsers",bootUsers);
        List<BootUser> list = (List<BootUser>)redisTemplate.opsForValue().get("bootUsers");
        return list;
    }

}

 

创建controller类文件

New file name BootUserController class files, the specific code as follows:

package com.yoodb.study.demo04;

import java.util.List;

import com.yoodb.study.demo04.bean.BootUser;
import com.yoodb.study.demo04.service.BootUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/myt")
public class BootUserController {
    @Autowired
    private BootUserService service;

    @RequestMapping("/getUsers")
    public List<BootUser> getUsers() {
        List<BootUser> list = service.getUsers();
        return list;
    }

}

 

 After mapper interface, xml files and physical files, service layer, controller layer is created, as shown in the directory:

  Project begining

After the start of the project access request address:

http://localhost:8080/myt/getUsers

Output through a browser to access the following information:

[{"id":"1","name":"admin","detail":"欢迎关注“Java精选”微信公众号,专注程序员推送一些Java开发知识,包括基础知识、各大流行框架(Mybatis、Spring、Spring Boot等)、大数据技术(Storm、Hadoop、MapReduce、Spark等)、数据库(Mysql、Oracle、NoSQL等)、算法与数据结构、面试专题、面试技巧经验、职业规划以及优质开源项目等。其中一部分由小编总结整理,另一部分来源于网络上优质资源,希望对大家的学习和工作有所帮助。"}]

 

Spring Boot从入门到精通(六)集成Redis实现缓存机制(项目源码springboot-study-demo04)地址:

https://github.com/yoodb/springboot

到此讲完了,Spring Boot集成Redis实现缓存机制,实际上就这么简单。不过需要注意使用的时候遇到的坑。~~

Guess you like

Origin www.cnblogs.com/MrYoodb/p/12422522.html