问题描述
我在一个项目中使用const express = require('express');
const ejs = require('ejs');
const passport = require('passport');
const flash = require('express-flash');
const session = require('express-session');
const bcrypt = require('bcrypt');
const monk = require('monk');
const app = express();
//connects to database
const db = monk(process.env.MONGO_URL || 'localhost/shop');
//connect to database and making collection if does not exist
const users = db.get('users');
//set view engine to ejs
app.set('view engine','ejs');
app.use(express.urlencoded({ extended: false}))
app.use(express.static(__dirname + '/views/partials'))
app.use(flash());
app.use(session({
secret: 'secret',resave: false,saveUninitialized: false
}))
app.use(passport.initialize());
app.use(passport.session());
//only use below when passport authentication is ready
//app.use(passport.session())
function validRegister(user) {
//checking client is sending username,email and password
return user.name && user.name.toString() !== '' &&
user.email && user.email.toString() !== '' &&
user.password && user.password.toString() !== '';
}
//use res.render to look up an ejs file
//home page
app.get('/',function(req,res) {
res.render('pages/index');
});
app.get('/success',res) {
res.json('Successful login');
});
app.get('/fail',res) {
res.json('login attempt Failed')
});
app.post('/register',(req,res) => {
const { name,email,password} = req.body;
let errors = [];
if (!name || !email || !password) {
errors.push({ msg: 'Please enter all fields' });
}
if (password != password) {
errors.push({ msg: 'Passwords do not match' });
}
if (password.length < 6) {
errors.push({ msg: 'Password must be at least 6 characters' });
}
if (errors.length > 0) {
res.json('fuck');
} else {
User.findOne({ email: email }).then(user => {
if (user) {
errors.push({ msg: 'Email already exists' });
}else {
const newUser = new User({
name,password
});
bcrypt.genSalt(10,(err,salt) => {
bcrypt.hash(newUser.password,salt,hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => {
req.flash(
'success_msg','You are Now registered and can log in'
);
res.redirect('/');
})
.catch(err => console.log(err));
});
});
}
});
}
});
app.listen(5000);
console.log('Server running on port 5000');
来缓存一些键和值。
MemoryCache
如上所述,我的密钥已过期。另外,我还将相同的密钥存储在private bool CacheEntries<T>(MemoryCache memoryCache,string cacheKey,T value,Configuration config,Action<MemoryCacheEntryOptions> otherOptions = null)
{
int minutes = randomGenerator.Next(config.LowTime,config.HighTime);
MemoryCacheEntryOptions options = new MemoryCacheEntryOptions()
{
Size = config.Size,Priority = config.Priority,AbsoluteExpirationRelativetoNow = TimeSpan.FromMinutes(minutes)
};
if (otherOptions != null) otherOptions(options);
CacheKeys.Add(cacheKey);
memoryCache.Set<T>(cacheKey,value,options);
return true;
}
CacheKeys
数据结构中,以备后用。有什么方法可以在我的HashSet
上附加一个侦听器,只要它过期了,就应该调用该侦听器,这样我也可以从MemoryCache
CacheKeys
删除这些键。基本上,我希望与HashSet
和CacheKeys
中的内容保持一致。
这可能吗?
解决方法
您似乎正在使用Microsoft.Extensions.Caching.Memory中的Platform Extensions对象。在缓存中设置项目的值时,可以对MemoryCacheEntryOptions对象使用MemoryCacheEntryOptions.PostEvictionCallbacks
属性:
获取或设置回调将在从缓存中逐出缓存条目后触发。
或者,如果可以更改为MemoryCache
的System.Runtime.Caching版本,则可以在设置值时使用CacheItemPolicy
。来自the documentation:
CacheItemPolicy实例包含可以与缓存条目关联的信息。例如,要从缓存中删除缓存条目时,会将CacheEntryUpdateArguments对象传递给回调方法。 CacheEntryUpdateArguments对象的UpdatedCacheItemPolicy属性可以将引用传递给CacheItemPolicy实例,该实例可以包括有关缓存项的收回和到期详细信息。
该版本MemoryCache
的另一种选择是调用CreateCacheEntryChangeMonitor
:
CreateCacheEntryChangeMonitor方法创建一个CacheEntryChangeMonitor实例。这种专用的更改监视器用于监视在键集合中指定的缓存条目,并在条目更改时触发事件。
由于以下任何原因,被监视的条目被视为已更改:
在调用CreateCacheEntryChangeMonitor方法时,该键不存在。在这种情况下,结果CacheEntryChangeMonitor实例将立即设置为更改状态。这意味着当代码随后绑定更改通知回调时,该回调将立即触发。
关联的缓存条目已从缓存中删除。如果该条目被显式删除,到期或驱逐以恢复内存,则可能会发生这种情况