Redis缓存优化案例

案例需求

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

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

pom.xml

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

    <groupId>com.cncs</groupId>
    <artifactId>redis-case</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>redis-case Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

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

    <dependencies>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.20</version>
        </dependency>

        <!--jedis-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.1</version>
        </dependency>
        <!--json-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.15</version>
        </dependency>
        <!--jdbcTemplate-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <finalName>redis-case</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8888</port>
                    <uriEncoding>UTF-8</uriEncoding>
                </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<Province> 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

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <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 () {
                            //创建<option>
                            var option = "<option value='" + this.id + "'>" + this.name + "</option>";
                            //追加到select
                            province.append(option);
                        })
                    }
                })
            });
        </script>
    </head>
    <body>
        <select id="province">
            <option>--请选择--</option>
        </select>
    </body>
</html>

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

  • 数据库的数据一旦发生改变,则需要更新缓存。
  • 数据库的表执行 增删改的相关操作,需要将redis缓存数据情况,再次存入
  • 在service对应的增删改方法中,将redis数据删除。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值