Nestjs中操作mysql数据库可以使用Nodejs封装的DB库,也可以使用TypeORM。下面我们主要给大家讲讲在Nestjs中使用TypeORM操作mysql数据库
1、Redis 字符串数据类型的相关命令用于管理 redis 字符串值。
基本语法: 查看所有的key: keys * 普通设置: set key value 设置并加过期时间: set key value EX 30 表示30秒后过期 获取数据: get key 删除指定数据: del key 删除全部数据: flushall 查看类型: type key 设置过期时间: expire key 20 表示指定的key5秒后过期
2、Redis列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素到列表的头部(左边)或者尾部(右边)
基本语法: 列表右侧增加值: rpush key value 列表左侧增加值: lpush key value 右侧删除值: rpop key 左侧删除值: lpop key 获取数据: lrange key 删除指定数据: del key 删除全部数据: flushall 查看类型: type key
3、Redis 的 Set 是 String 类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据。它和列表的最主要区别就是没法增加重复值
基本语法: 给集合增数据: sadd key value 删除集合中的一个值: srem key value 获取数据: smembers key 删除指定数据: del key 删除全部数据: flushall
4、Redis hash 是一个string类型的field和value的映射表,hash特别适合用于存储对象。
基本语法: 设置值hmset : hmset zhangsan name "张三" age 20 sex “男” 设置值hset : hset zhangsan name "张三" 获取数据: hgetall key 删除指定数据: del key 删除全部数据: flushall
5、Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。
发布
client.publish('testPublish', 'message from publish.js');
订阅
client.subscribe('testPublish');
client.on('message', function(channel, msg){
console.log('client.on message, channel:', channel, ' message:', msg);
});
npm install nestjs-redis --save2、用到redis的模块中注册RedisModule
options是一个对象,里面配置了连接redis服务器的信息
import { RedisModule} from 'nestjs-redis'
@Module({
imports: [
RedisModule.register(options)
],
})
关于options
let options={
port: 6379,
host: '127.0.0.1',
password: '',
db: 0
}
3、创建一个cache.service.ts 服务 封装操作redis的方法
import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';
@Injectable()
export class CacheService {
public client;
constructor(private redisService: RedisService) {
this.getClient();
}
async getClient() {
this.client = await this.redisService.getClient()
}
//设置值的方法
async set(key:string, value:any, seconds?:number) {
value = JSON.stringify(value);
if(!this.client){
await this.getClient();
}
if (!seconds) {
await this.client.set(key, value);
} else {
await this.client.set(key, value, 'EX', seconds);
}
}
//获取值的方法
async get(key:string) {
if(!this.client){
await this.getClient();
}
var data = await this.client.get(key);
if (!data) return;
return JSON.parse(data);
}
}
4、调用cache.service.ts 里面封装的方法操作redis数据库
await this.cache.set('username','李四');
await this.cache.get('username')