Redis做缓存MySQL登录实现

package com.mind.core.db;

import com.mind.core.db.impl.CacheService;
import com.mind.core.db.impl.DBService;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by Lovell on 16/6/22.
 */
public class DaoTest {
    public static void main(String[] args) throws IOException, SQLException {

        Dao dao = new Dao();
        dao.start();

        String id="2";

        String sql="select * from login where id='"+id+"'";

        String name = null;
        Jedis jedis = CacheService.getInstance().getJedisPool().getResource();

        if(jedis.hexists("id"+id, "name")){
            name = jedis.hget("id"+id, "name");
            System.out.println("Welcome Redis! User "+ name +" login success");
        }else{
            Connection conn = DBService.getInstance().getConnection();
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            if(rs.next()==false){
                System.out.println("MySQL no register, Please register first");
            }else{
                name = rs.getString("name");
                System.out.println("Welcome MySQL ! User "+name+" login success");
                jedis.hset("id"+id, "name", name);

                // 十秒钟就过期
                jedis.expire("id"+id, 10);
            }
        }
    }
}

  1. 用户登录首先判断是否在redis缓存中,如果在rRedis缓存中,直接登录成功;

  2. 若用户未在Redis缓存,则访问MySQL,判断用户是否存在,如果不存在,则提示用户注册;如果存在,则登录成功;

  3. 在MySQL存在并登录成功的同时,将改条数据用Redis Hash类型进行缓存,并设置过期时间为10秒;

  4. 设置Redis最大内存,若超出内存范围,则使用FIFO方式进行清除。

     在redis.conf文件中找到并设置即可:maxmemory  10240000



你可能感兴趣的:(MySQL,Redis)