Redis缓存优化案例

案例需求

  • 提供index.html页面,页面中有一个省份 下拉列表
  • 当页面加载完成后,发送ajax请求,加载所有省份

优化说明:未使用redis缓存省份的时候,每次访问页面都要向数据库查询数据,效率十分低。改用redis缓存数据后,每次查询数据先从redis查,有数据则快速获取,没有再从mysql数据库查询。

pom.xml



<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.cncsgroupId>
    <artifactId>redis-caseartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>warpackaging>

    <name>redis-case Maven Webappname>
    
    <url>http://www.example.comurl>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.20version>
        dependency>

        
        <dependency>
            <groupId>redis.clientsgroupId>
            <artifactId>jedisartifactId>
            <version>2.9.1version>
        dependency>
        
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.9.0version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.9.0version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-annotationsartifactId>
            <version>2.9.0version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.15version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.0.2.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.0.1version>
            <scope>providedscope>
        dependency>

    dependencies>

    <build>
        <finalName>redis-casefinalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.mavengroupId>
                <artifactId>tomcat7-maven-pluginartifactId>
                <version>2.2version>
                <configuration>
                    <port>8888port>
                    <uriEncoding>UTF-8uriEncoding>
                configuration>
            plugin>
        plugins>
    build>
project>

配置文件

jedis.properties

host=127.0.0.1
port=6379
maxTotal=50
maxIdle=10

druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000

工具类

JDBCUtils

public class JDBCUtils {

    private static DataSource ds ;

    static {

        try {
            //1.加载配置文件
            Properties pro = new Properties();
            //使用ClassLoader加载配置文件,获取字节输入流
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);

            //2.初始化连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接池对象
     */
    public static DataSource getDataSource(){
        return ds;
    }


    /**
     * 获取连接Connection对象
     */
    public static Connection getConnection() throws SQLException {
        return  ds.getConnection();
    }
}

JedisPoolsUtils

public class JedisPoolUtils {

    private static JedisPool jedisPool;

    static {
        //加载配置文件
        InputStream in = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
        //创建properties对象
        Properties properties = new Properties();
        //关联文件
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //读取属性文件并配置
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal")));
        config.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle")));
        //初始化jedis连接池
        jedisPool = new JedisPool(config,properties.getProperty("host"),Integer.parseInt(properties.getProperty("port")));
    }

    /**
     * 获取Jedis连接
     *
     * @return
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * 关联连接 归还连接到连接池
     */
    public static void close(){
        jedisPool.close();
    }

}

servlet

provinceServlet

@WebServlet("/provinceServlet")
public class provinceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取数据
        /*IProvinceService provinceService = new ProvinceServiceImpl();
        List provinces = provinceService.findAll();
        //将对象序列化
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(provinces);*/

        IProvinceService provinceService = new ProvinceServiceImpl();
        String json = provinceService.findAllJson();

        System.out.println(json);
        //响应
        //设置响应类型
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }
}

service

ProvinceServiceImpl

public class ProvinceServiceImpl implements IProvinceService {

    private IProvinceDao provinceDao=new ProvinceDaoImpl();

    @Override
    public List<Province> findAll() {
        return provinceDao.findAll();
    }

    @Override
    public String findAllJson() {
        //先从redis查询
        Jedis jedis = JedisPoolUtils.getJedis();
        String province_json = jedis.get("province");
        //判断redis中数据是否存在
        //不存在,先从mysql查询
        if(province_json == null || province_json.length() == 0){
            System.out.println("从mysql查询");
            List<Province> list = provinceDao.findAll();
            ObjectMapper mapper = new ObjectMapper();
            try {
                province_json = mapper.writeValueAsString(list);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            //存入redis
            jedis.set("province",province_json);
        }else {
            //存在,直接从redis返回数据
            System.out.println("从redis缓存查询");
        }
        return province_json;
    }
}

dao

ProvinceDaoImpl

public class ProvinceDaoImpl implements IProvinceDao {

    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Province> findAll() {
        return jdbcTemplate.query("select * from province",new BeanPropertyRowMapper<Province>(Province.class));
    }
}

Web

index.html


<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="js/jquery-3.3.1.min.js">script>
        <script>
            $(function () {
                //发送ajax请求
                $.ajax({
                    url: "provinceServlet",
                    dataType: "json",
                    type: "GET",
                    success: function (data) {
                        //获取select
                        var province = $("#province");
                        //遍历json数组
                        $(data).each(function () {
                            //创建
                            var option = " + this.name + "";
                            //追加到select
                            province.append(option);
                        })
                    }
                })
            });
        script>
    head>
    <body>
        <select id="province">
            <option>--请选择--option>
        select>
    body>
html>

注意:使用redis缓存一些不经常发生变化的数据。

  • 数据库的数据一旦发生改变,则需要更新缓存。
  • 数据库的表执行 增删改的相关操作,需要将redis缓存数据情况,再次存入
  • 在service对应的增删改方法中,将redis数据删除。

你可能感兴趣的:(Redis)