redis操作包括String、List、Hash、Set、SortedSet
为什么要使用redis
将数据存储在内存中,速度快,支持多种数据结构
怎么样选择合适的数据结构
string:存储的数据量不是很庞大,一些信息
list:一个东西对应到多个东西,且要求有顺序
hash:用hash实现的东西都可以用string去实现,相比于string要节省空间
set:不允许有重复元素,有交集差集并集
sortedset: 类似于排行榜的功能
redis还有那些应用
分布式锁、发布和订阅(推送)
基本操作
//启动redis
$ redis-server &
$ redis-cli
keys * 查看所有数据
flushall 清除所有数据
参考文档
http://www.runoob.com/redis/redis-tutorial.html
string类型
List类型
Hash类型
Set类型
SortedSet类型
微博功能设计
编程实践框架
配置参数和工具类
编写时间工具和配置解析工具
其中config.ini是配置文件、time_utils.py是时间工具、conf_prase是配置解析文件
# config.ini
#环境配置
# test/online
[environ]
env = test
[online-redis]
host=127.0.0.1
port = 6379
user =
password =
db= 0
[test-redis]
host=192.168.0.1
port = 6379
user =
password =
db= 0
# encoding = utf-8
#conf_prase.py
'''
配置解析工具
'''
try:
import configparser
except ImportError:
import ConfigParser as configparser
config = configparser.ConfigParser()
class ConfParse(object):
"""
配置解析
"""
REDIS_CONF = '%s-redis'
@classmethod
def _get_env(cls,filename='../conf/config.ini'):
"""
获取选择的环境:线上/线下
:param filename:
:return:
"""
config.read(filename)
return config.get('environ','env')
@classmethod
def get_redis_conf(cls):
"""
获取redis的相关配置:[host、port、user、passwd、db]
:return:
"""
select_section = cls.REDIS_CONF % cls._get_env()
return [config.get(select_section, item) for item in config.options(select_section)]
#print(ConfParse.get_redis_conf())
# encoding = utf-8
# time_utils.py
"""
时间工具类
"""
import time
class TimeUtils(object):
"""
时间工具
"""
@classmethod
def get_current_timestamp(cls):
"""
获取当前时间戳
:return:
"""
return int(time.time())
@classmethod
def timestamp_2_data_str(cls,timestamp):
"""
时间戳转换成时间字符串
:param timestamp:
:return:
"""
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
对象定义和常量定义
# encoding = utf-8
# wb_model.py
"""
微博中所涉及到的model的定义
"""
import json
class TJson(object):
"""
对象转json
"""
@property
def t_json(self):
return json.dumps(self.__dict__)
class User(TJson):
"""
用户对象
"""
def __init__(self,name,sex,age,signature=''):
"""
初始化函数
:param name:
:param sex:
:param age:
:param signature:
"""
self.id = -1
self.name = name
self.sex = sex
self.age = age
self.signature = signature
@property
def sign(self):
return self.signature
@sign.setter
def sign(self,signature):
self.signature=signature
class WeiBo(TJson):
"""
微博对象
"""
def __init__(self,user_id,text,click_count=0):
"""
初始化函数
:param user_id:
:param text:
:param click_count:
"""
self.id = -1
self.user_id = user_id
self.text = text
self.click_count = click_count
self.timestamp = 0
@property
def click(self):
return self.click_count
@click.setter
def click(self,click_count):
self.click_count += click_count
class Topic(TJson):
"""
话题对象
"""
def __init__(self,logo,text):
"""
初始化话题
:param logo:
:param text:
"""
self.id = -1
self.logo = logo
self.text = text
topic = Topic("www.weibo.com","这是一个微博话题")
print(topic.t_json)
# encoding = utf-8
# constants.py
"""
定义常量
"""
class RedisKey(object):
"""
redis 涉及到的key定义
"""
USER_ID = 'user_id' #用户id生成计数
WEIBO_ID = 'weibo_id' #微博id生成计数
TOPIC_ID = 'topic_id' #话题id生成计数
USER_PREFIX = 'user_%s' #用户个人信息
TOPIC_PREFIX = 'topic_%s' #话题信息
JOIN_IN_TOPIC_PREFIX = 'join_in_topic_%s' #参与话题的用户存储
USER_WEIBO_PREFIX = 'user_weibo_%s' #用户发表的微博
USER_ATTENTION_PREFIX = 'user_attention_%s' #用户关注其他的用户
USER_ATTENTION_WEIBO_PREFIX = 'user_attention_weibo_%s' #关注用户发表的微博
USER_FANS_PREFIX = 'user_fans_%s' #用户的粉丝
WEIBO = 'weibo' #微博广场
WEIBO_INDEX = 'weibo_index' #用户指数
业务操作的实现
# encoding = utf-8
# test_user_op.py
"""
user相关动作测试
"""
import unittest
from model.wb_model import User
from test.test_base import BaseTest
from utils.redis_op import RedisOP
class UserOPTest(BaseTest):
"""
user op test
"""
def test_user_op(self):
"""
测试user相关操作
:return:
"""
user_1 = User('qinyi','m',25,'helloworld')
user_1_id = RedisOP.store_user_object(user_1)
self.assertTrue(user_1_id == 1)
user_1 = RedisOP.get_user_by_id(user_1_id)
user_2 = User('redis','m',5,'helloredis')
user_2_id = RedisOP.store_user_object(user_2)
self.assertTrue(user_2_id == 2)
user_2 = RedisOP.get_user_by_id(user_2_id)
RedisOP.store_user_attention(user_1, user_2)
self.assertEqual(RedisOP.get_user_attention_ids(user_1), [str(user_2_id)])
self.assertEqual(RedisOP.get_user_fans_ids(user_2), [str(user_1_id)])
# encoding = utf-8
# wb_model.py
"""
微博中所涉及到的model的定义
"""
import json
class TJson(object):
"""
对象转json
"""
@property
def t_json(self):
return json.dumps(self.__dict__)
class User(TJson):
"""
用户对象
"""
def __init__(self,name,sex,age,signature=''):
"""
初始化函数
:param name:
:param sex:
:param age:
:param signature:
"""
self.id = -1
self.name = name
self.sex = sex
self.age = age
self.signature = signature
@property
def sign(self):
return self.signature
@sign.setter
def sign(self,signature):
self.signature=signature
class WeiBo(TJson):
"""
微博对象
"""
def __init__(self,user_id,text,click_count=0):
"""
初始化函数
:param user_id:
:param text:
:param click_count:
"""
self.id = -1
self.user_id = user_id
self.text = text
self.click_count = click_count
self.timestamp = 0
@property
def click(self):
return self.click_count
@click.setter
def click(self,click_count):
self.click_count += click_count
class Topic(TJson):
"""
话题对象
"""
def __init__(self,logo,text):
"""
初始化话题
:param logo:
:param text:
"""
self.id = -1
self.logo = logo
self.text = text
topic = Topic("www.weibo.com","这是一个微博话题")
print(topic.t_json)