Redis学习
1、Redis是什么?
- 相对MySql、SqlServer和Oracle来说,Redis是NOSQL,也就是非关系型数据库
2、为什么要学习Redis
- 与传统数据库不同,Redis可以将一些长期不变的数据存放在内存中,这样的存储方式使得读取数据的速度加快,常用于高并发的访问场景
3、Redis的存储方式
- 通过key、value键值对的形式存储数据,其中最常用的是**Map<String,String>**这样的存储方式,value通常是json数据格式
4、Java中怎样使用Redis
-
导入Jedis的两个jar包(注意导入的包在自己创建的WEB-INF下的lib文件夹里)
-
使用Jedis连接池实现数据的存储
-
src下创建properties文件
-
创建工具类方便获得Jedis对象
public class JedisUtils { private static int maxTotal; private static int maxIdle; private static String host; private static int port; private static JedisPool pool; private static Jedis jedis; static { //使用properties文件读取配置信息 InputStream inputStream = JedisUtils.class.getClassLoader().getResourceAsStream("redis.properties"); Properties properties = new Properties(); //记载配置文件 try { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); } //获取键对应的值,并将字符串转为数字类型 maxTotal = Integer.parseInt(properties.getProperty("maxTotal")); maxIdle = Integer.parseInt(properties.getProperty("maxIdle")); host = properties.getProperty("host"); port = Integer.parseInt(properties.getProperty("port")); //1、配置连接池 JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(maxTotal);//最大连接数量 config.setMaxIdle(maxIdle);//最大空闲数量 //2、创建连接池 pool = new JedisPool(config, host, port); } public static Jedis getJedis() { //开启一个连接 jedis = pool.getResource(); //返回一个连接 return jedis; } public static void close() { jedis.close(); } }
-