1.概述
2.下载安装
redis中文网
3. 命令操作
3.1 数据结构
3.2 命令操作
3.3 redis持久化
如果修改完配置文件,需要按以下方式重启一下
AOF对性能要求比较大,总在持久化。
如果修改完配置文件,需要按以下方式重启一下
3.4 Jedis
扫描二维码关注公众号,回复:
13302534 查看本文章
Jedis 操作五种数据结构:
package cn.itcast.jedis.test;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* jedis 测试类
*/
public class JedisTest {
/**
* 快速入门
*/
@Test
public void test1() {
// 1. 获取连接
Jedis jedis = new Jedis("localhost", 6379); // ip 和 端口号
// 2. 操作
jedis.set("username", "zhangsan");
// 3. 关闭拦截
jedis.close();
}
@Test
/**
* 操作字符串 String
*/
public void test2() {
Jedis jedis = new Jedis(); // 如果使用空参构造,默认值为 “localhost”,6379端口
jedis.set("username", "zhangsan");
String name = jedis.get("username");
System.out.println(name);
// 可以使用setex()方法存储,可以指定过期时间的 key value
jedis.setex("activecode", 20, "hehe"); // 将activecode,hehe键值对存入redis,并在20秒后自动删除。
jedis.close();
}
@Test
/**
* 操作 hash结构
*/
public void test3() {
Jedis jedis = new Jedis();
//存储
jedis.hset("user", "name", "lisi");
jedis.hset("user", "age", "23");
jedis.hset("user", "gender", "male");
// 获取
String name = jedis.hget("user", "name");
System.out.println(name);
// 获取所有数据
Map<String,String> user = jedis.hgetAll("user");
Set<String> keySet = user.keySet();
for (String key:keySet){
//获取value
String value = user.get(key);
System.out.println(key +"+" +value);
}
jedis.close();
}
@Test
/**
* 操作 列表 list
*/
public void test4(){
Jedis jedis = new Jedis();
//存储
jedis.lpush("mylist","a","b","c"); // cba
jedis.rpush("mylist","a","b","c"); // abc
// 范围获取
List<String> mylist = jedis.lrange("mylist",0,-1);//cbaabc
System.out.println(mylist);
// list 弹出
String ele1 = jedis.lpop("mylist"); //c
System.out.println(ele1);
String ele2 = jedis.rpop("mylist");// c
System.out.println(ele2);
List<String> mylist2 = jedis.lrange("mylist",0,-1);//baab
System.out.println(mylist2);
jedis.close();
}
@Test
/**
* 操作 set 不允许重复元素
*/
public void test5(){
Jedis jedis = new Jedis();
jedis.sadd("myset","java","php","c++");
Set<String> myset = jedis.smembers("myset");
System.out.println(myset);
jedis.close();
}
@Test
/**
* 操作 sortedset 不允许重复元素
*/
public void test6(){
Jedis jedis = new Jedis();
jedis.zadd("mysortset",3,"lisi");
jedis.zadd("mysortset",10,"wang");
Set<String> mysortset = jedis.zrange("mysortset", 0, -1);
System.out.println(mysortset);
jedis.close();
}
}
jedis 连接池: JedisPool
@Test
/**
* jedis 连接池使用
*/
public void test7(){
// 0. 创建一个配置对象,还有很多配置
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(50); //最大连接数
config.setMaxIdle(10);//空闲连接
// 1.创建Jedis连接池对象
JedisPool jedisPool = new JedisPool(config,"localhost",6379);
// 2. 获取连接
Jedis jedis = jedisPool.getResource();
// 3. 使用
jedis.set("username","zhang");
String username = jedis.get("username");
System.out.println(username);
// 4. 关闭 归还到连接池中
jedis.close();
}
Jedis 连接池工具类
jedis.properties配置文件 src目录下
host=localhost
port=6379
maxTotal=50
maxIdle=10
JedisPoolUtils.java 工具类
package cn.itcast.jedis.util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* JedisPool工具类
* 加载配置文件,配置连接池参数
* 提供获取连接的方法
*/
public class JedisPoolUtils {
// 工具类一般是静态的
private static JedisPool jedisPool;
//静态代码块:类一加载就读取配置文件。
static {
//读取配置文件
InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
//创建Properties对象
Properties pro = new Properties();
//关联文件
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//获取数据,设置到JedisPoolConfig里
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal"))); //获取的一个String,要变成int
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
// 初始化JedisPool
jedisPool = new JedisPool(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));
}
/**
* 获取连接方法
*/
public static Jedis getJedis(){
return jedisPool.getResource();
}
}
测试
@Test
/**
* JedisPool工具类使用
*/
public void test8(){
// 通过连接池工具类获取
Jedis jedis = JedisPoolUtils.getJedis();
// 3. 使用
jedis.set("username","zhang");
String username = jedis.get("username");
System.out.println(username);
// 4. 关闭 归还到连接池中
jedis.close();
}
3.5 案例
环境搭建:
1)建立数据库
CREATE DATABASE day23;
USE day23;
CREATE TABLE province(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL
);
INSERT INTO province VALUES(NULL,'北京');
INSERT INTO province VALUES(NULL,'上海');
INSERT INTO province VALUES(NULL,'广州');
INSERT INTO province VALUES(NULL,'陕西');
SELECT * FROM province;
domain文件夹,定义数据库中存储的数据
Province.java
package cn.itcast.domain;
public class Province {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
util文件夹 工具类
JDBCUtils.java
package cn.itcast.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Properties;
/**
* JDBC工具类 Durid连接池
*/
public class JDBCUtils {
private static DataSource ds; // 数据库连接池对象
static {
try {
// 1.加载配置文件
Properties pro = new Properties();
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();
}
}
druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///day23
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
dao文件夹执行sql语句
ProvinceDao接口
package cn.itcast.dao;
import cn.itcast.domain.Province;
import java.util.List;
public interface ProvinceDao {
public List<Province> findAll();
}
ProvinceDaoImpl。java实现类
package cn.itcast.dao;
import cn.itcast.domain.Province;
import cn.itcast.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class ProvinceDaoImpl implements ProvinceDao{
// 1. 声明成员变量 jdbctemplement
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
public List<Province> findAll() {
// 1.定义sql
String sql = "select * from province";
// 2. 执行sql
List<Province> list = template.query(sql,new BeanPropertyRowMapper<Province>(Province.class));
return list;
}
}
service文件夹
接口
package cn.itcast.service;
import cn.itcast.domain.Province;
import java.util.List;
public interface ProvinceService {
public List<Province> findAll();
}
实现类
package cn.itcast.service;
import cn.itcast.dao.ProvinceDao;
import cn.itcast.dao.ProvinceDaoImpl;
import cn.itcast.domain.Province;
import java.util.List;
public class ProvinceServiceImpl implements ProvinceService{
private ProvinceDao dao = new ProvinceDaoImpl();
@Override
public List<Province> findAll() {
return dao.findAll();
}
}
web。servlet文件夹
package cn.itcast.web.servlet;
import cn.itcast.domain.Province;
import cn.itcast.service.ProvinceService;
import cn.itcast.service.ProvinceServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/ProvinceServlet")
public class ProvinceServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 调用service查询
ProvinceService service = new ProvinceServiceImpl();
List<Province> list = service.findAll();
// 2. 序列化list转为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(list);
//System.out.println(json);
// 3. 响应结果
resp.setContentType("application/json;charset=utf-8");
resp.getWriter().write(json);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
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请求,加载所有省份
$.get("ProvinceServlet",{
},function (data) {
// [{"id":1,"name":"北京"},{"id":2,"name":"上海"},{"id":3,"name":"广州"},{"id":4,"name":"陕西"}]
//1.获取select
var province = $("#province");
// 2.遍历json数组
$(data).each(function () {
//3.创建<option>
var option = "<option name='"+this.id+"'>"+this.name+"</option>";
// 4.调用select的append追加option
province.append(option);
});
});
});
</script>
</head>
<body>
<select id="province">
<option>--请选择省份--</option>
</select>
</body>
</html>
service的接口
package cn.service;
import cn.domain.Province;
import java.util.List;
public interface ProvinceService {
public List<Province> findAll();
public String findAllJson();
}
service的实现类
package cn.service;
import cn.dao.ProvinceDao;
import cn.dao.ProvinceDaoImpl;
import cn.domain.Province;
import cn.jedis.util.JedisPoolUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;
import java.util.List;
public class ProvinceServiceImpl implements ProvinceService{
ProvinceDao dao = new ProvinceDaoImpl();
@Override
public List<Province> findAll() {
List<Province> list = dao.findAll();
return list;
}
/**
* 使用redis缓存
* @return
*/
@Override
public String findAllJson() {
// 1. 先从redis查询数据
// 1.1 获取redis客户端连接
Jedis jedis = JedisPoolUtils.getJedis();
String province_json = jedis.get("province");
// 2. 判断 province_json数据是否为null
if (province_json == null || province_json.length()==0){
// redis中没有数据
System.out.println("redis没数据,查询数据库...");
// 2.1从数据库中查询
List<Province> ps = dao.findAll();
// 2.2序列化json
ObjectMapper mapper = new ObjectMapper();
try {
province_json = mapper.writeValueAsString(ps);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
// 2.3 将json数据存入redis
jedis.set("province",province_json);
jedis.close();
}
return province_json;
}
}
还有servlet需修改
package cn.web.servlet;
import cn.domain.Province;
import cn.service.ProvinceService;
import cn.service.ProvinceServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/ProvinceServlet")
public class ProvinceServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*ProvinceService service = new ProvinceServiceImpl();
List<Province> list = service.findAll();
//序列化为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(list);*/
// 采用redis方式
ProvinceService service =new ProvinceServiceImpl() ;
String json = service.findAllJson();
//响应结果
resp.setContentType("application/json;charset=utf-8");
resp.getWriter().write(json);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}