1、redis 介绍
Redis 是齐全开源的,是一个高性能的 key-value 数据库。
redis 的劣势
性能高 – Redis能读的速度是110000次/s,写的速度是81000次/s 。
丰盛的数据类型 – Redis反对二进制案例的 Strings, Lists, Hashes, Sets
及 Ordered Sets
数据类型操作。
原子 – Redis的所有操作都是原子性的,意思就是要么胜利执行要么失败齐全不执行。单个操作是原子性的。多个操作也反对事务,即原子性,通过MULTI和EXEC指令包起来。
丰盛的个性 – Redis还反对 publish/subscribe
, 告诉, key 过期等等个性。。
2、在我的项目中的利用
在游戏服务器中的利用次要有上面几个场景:
基于redis
的高性能,所以咱们当做跨服的数据存储应用
基于redis
的公布订阅性能,咱们当做服务器之间的音讯公布应用,统领所有的服务器
基于redis
的排序功能,咱们当做跨服的排行榜应用。
3、代码展现
在我的项目中退出上面的依赖
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId></dependency>
如果你应用springboot搭建的我的项目,能够退出上面到pom
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency>
1、数据存储
数据的存储比较简单,惯例的应用就行
@Componentpublic class RedisUtil { public static RedisUtil util; public RedisUtil(@Autowired JedisPool jedisPool) { this.jedisPool = jedisPool; RedisUtil.util = this; } public static RedisUtil getInstance(){ return util; } @Autowired private JedisPool jedisPool; /** * 向Redis中存值,永恒无效 */ public String set(String key, String value) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.set(key, value); } catch (Exception e) { return "0"; } finally { jedis.close(); } } /** * 依据传入Key获取指定Value */ public String get(String key) { Jedis jedis = null; String value; try { jedis = jedisPool.getResource(); value = jedis.get(key); } catch (Exception e) { return "0"; } finally { jedis.close(); } return value; } /** * 校验Key值是否存在 */ public Boolean exists(String key) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.exists(key); } catch (Exception e) { return false; } finally { jedis.close(); } } /** * 删除指定Key-Value */ public Long del(String key) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.del(key); } catch (Exception e) { return 0L; } finally { jedis.close(); } } /** * 分布式锁 * @param key * @param value * @param time 锁的超时工夫,单位:秒 * * @return 获取锁胜利返回"OK",失败返回null */ public String getDistributedLock(String key,String value,int time){ Jedis jedis = null; String ret = ""; try { jedis = jedisPool.getResource(); ret = jedis.set(key, value, new SetParams().nx().ex(time)); return ret; } catch (Exception e) { return null; } finally { jedis.close(); } } public void pub(){ jedisPool.getResource().publish("test","msg"); } }