Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
Bu kılavuzda, bir özelliği Node.js uygulamanız için hedeflenen hedef kitlelere dağıtma amacıyla hedefleme filtresini kullanacaksınız. Hedefleme filtresi hakkında daha fazla bilgi için bkz . Özellikleri hedeflenen hedef kitlelere dağıtma.
Önkoşullar
- Aktif bir aboneliğe sahip bir Azure hesabı. Ücretsiz bir tane oluşturun.
- Mağaza oluşturma öğreticisinde gösterildiği gibi bir Uygulama Yapılandırma deposu.
- Hedefleme filtresine sahip bir Beta özellik bayrağı. Özellik bayrağını oluşturun.
- Node.js LTS sürümleri.
Özellik bayrağıyla web uygulaması oluşturma
Bu bölümde, bir web sayfasının beta sürümüne erişimi denetlemek için Beta özellik bayrağını kullanan bir web uygulaması oluşturacaksınız.
Node.js Express projesi kurma
adlı
targeting-filter-tutorialbir klasör oluşturun ve projeyi başlatın.mkdir targeting-filter-tutorial cd targeting-filter-tutorial npm init -yAşağıdaki paketleri yükleyin.
npm install @azure/app-configuration-provider npm install @microsoft/feature-management npm install expressapp.js adlı yeni bir dosya oluşturun ve aşağıdaki kodu ekleyin.
const express = require("express"); const server = express(); const port = "8080"; server.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); });
Azure Uygulama Yapılandırması'na bağlanma
app.js güncelleştirin ve aşağıdaki kodu ekleyin.
// Existing code ... const appConfigEndpoint = process.env.AZURE_APPCONFIG_ENDPOINT; const { DefaultAzureCredential } = require("@azure/identity"); const { load } = require("@azure/app-configuration-provider"); const { FeatureManager, ConfigurationMapFeatureFlagProvider } = require("@microsoft/feature-management"); let appConfig; let featureManager; async function initializeConfig() { // Load feature flags from App Configuration. appConfig = await load(appConfigEndpoint, new DefaultAzureCredential(), { featureFlagOptions: { enabled: true, refresh: { enabled: true } } }); // Create feature manager with feature flag provider that accesses feature flags from App Configuration. featureManager = new FeatureManager( new ConfigurationMapFeatureFlagProvider(appConfig)); } // Use a middleware to refresh the configuration before each request. server.use((req, res, next) => { appConfig.refresh(); next(); }); // Existing code ...Özellik bayraklarını yüklemek, otomatik yenilemeyi etkinleştirmek ve daha sonra özellik bayraklarına erişmek için bir
FeatureManagernesne oluşturmak için Azure Uygulama Yapılandırması'na bağlanırsınız. Her istek öncesinde yenileme yapılandırmasına bir ara yazılım eklenir.Express sunucusunun yalnızca yapılandırma başarıyla başlatıldıktan sonra başlatıldığından emin olmak için kodu güncelleştirin.
// Existing code ... initializeConfig() .then(() => { // Start the express server. server.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); }); })
Özellik bayrağını kullanma
Express sunucusunun yol işleyicisini yapılandırmak için app.js dosyasına aşağıdaki kodu ekleyin. Sunucu , Beta özellik bayrağının etkinleştirilip etkinleştirilmediğine bağlı olarak farklı içeriklere hizmet eder.
// Existing code ...
server.get("/", async (req, res) => {
const isBetaEnabled = await featureManager.isEnabled("Beta");
const [title, message] = isBetaEnabled
? ["Beta Page", "This is a beta page."]
: ["Home Page", "Welcome."];
res.send(
`<!DOCTYPE html>
<html>
<head><title>${title}</title></head>
<body style="display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0;">
<h1 style="text-align: center; font-size: 5rem;">${message}</h1>
</body>
</html>`
);
});
initializeConfig()
// Existing code ...
Web uygulaması için hedeflemeyi etkinleştirme
Hedefleme etkin özellikleri değerlendirirken bir hedefleme bağlamı gereklidir. Özellik değerlendirmesi için bu bağlamı açıkça sağlamak için bunu yöntemine featureManager.isEnabled parametre olarak geçirebilirsiniz.
const isBetaEnabled = await featureManager.isEnabled("Beta", { userId: "UserA", groups: ["Group1"] });
Bir web uygulamasında hedefleme bağlamı, ITargetingContextAccessor arabirimi uygulanarak ortam bağlamı olarak da sağlanabilir. Ortam hedefleme bağlamı, hedeflenen bilgilerin her featureManager.isEnabled() çağrıya açıkça iletilmesi gerekmeden geçerli HTTP isteği gibi ortamdan otomatik olarak alındığını gösterir.
Bu öğreticide, çevresel hedefleme bağlamını kullanacaksınız.
Express sunucu bildiriminden sonra aşağıdaki kodu ekleyin. Bu, özellik yöneticisinin bir hedefleme bağlamı erişimcisi geri çağırması aracılığıyla hedefleme bağlamını otomatik olarak alabilmesine olanak tanıyarak geçerli isteği depolamak için
AsyncLocalStoragekullanır. Daha fazla ayrıntı için bkz. İstek bağlamı için AsyncLocalStorage kullanma.const express = require("express"); const server = express(); const port = 8080; const { AsyncLocalStorage } = require("async_hooks"); const requestAccessor = new AsyncLocalStorage(); // Use a middleware to store request context. server.use((req, res, next) => { // Store the request in AsyncLocalStorage for this request chain. requestAccessor.run(req, () => { next(); }); }); // Create a targeting context accessor that retrieves user data from the current request. const targetingContextAccessor = { getTargetingContext: () => { // Get the current request from AsyncLocalStorage. const request = requestAccessor.getStore(); if (!request) { return undefined; } const { userId, groups } = request.query; return { userId: userId, groups: groups ? groups.split(",") : [] }; } }; // Existing code ...FeatureManageroluşturulurken, hedefleme bağlamı erişimcisiniFeatureManagerOptionsöğesine geçirin.featureManager = new FeatureManager( new ConfigurationMapFeatureFlagProvider(appConfig), { targetingContextAccessor: targetingContextAccessor });
Önceki adımları tamamladıktan sonra ,app.js dosyanız artık aşağıdaki tam uygulamayı içermelidir.
const express = require("express");
const server = express();
const port = 8080;
const { AsyncLocalStorage } = require("async_hooks");
const requestAccessor = new AsyncLocalStorage();
// Use a middleware to store request context
server.use((req, res, next) => {
// Store the request in AsyncLocalStorage for this request chain
requestAccessor.run(req, () => {
next();
});
});
// Create a targeting context accessor that retrieves user data from the current request
const targetingContextAccessor = {
getTargetingContext: () => {
// Get the current request from AsyncLocalStorage
const request = requestAccessor.getStore();
if (!request) {
return undefined;
}
const { userId, groups } = request.query;
return {
userId: userId,
groups: groups ? groups.split(",") : []
};
}
};
const appConfigEndpoint = process.env.AZURE_APPCONFIG_ENDPOINT;
const { DefaultAzureCredential } = require("@azure/identity");
const { load } = require("@azure/app-configuration-provider");
const { FeatureManager, ConfigurationMapFeatureFlagProvider } = require("@microsoft/feature-management");
let appConfig;
let featureManager;
async function initializeConfig() {
// Load feature flags from App Configuration.
appConfig = await load(appConfigEndpoint, new DefaultAzureCredential(), {
featureFlagOptions: {
enabled: true,
refresh: {
enabled: true
}
}
});
// Create feature manager with feature flag provider that accesses feature flags from App Configuration and targeting context accessor.
featureManager = new FeatureManager(
new ConfigurationMapFeatureFlagProvider(appConfig),
{
targetingContextAccessor: targetingContextAccessor
});
}
// Use a middleware to refresh the configuration before each request
server.use((req, res, next) => {
appConfig.refresh();
next();
});
server.get("/", async (req, res) => {
const isBetaEnabled = await featureManager.isEnabled("Beta");
const [title, message] = isBetaEnabled
? ["Beta Page", "This is a beta page."]
: ["Home Page", "Welcome."];
res.send(
`<!DOCTYPE html>
<html>
<head><title>${title}</title></head>
<body style="display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0;">
<h1 style="text-align: center; font-size: 5rem;">${message}</h1>
</body>
</html>`
);
});
// Initialize the configuration and start the server
initializeConfig()
.then(() => {
// Start the express server.
server.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
})
Filtrelemeyi hedefleme işlemi
AZURE_APPCONFIG_ENDPOINT adlı ortam değişkenini Azure portalındaki mağazanıza genel bakış bölümünde bulunan Uygulama Yapılandırma deponuzun uç noktasına ayarlayın.
Windows komut istemini kullanıyorsanız, aşağıdaki komutu çalıştırın ve değişikliğin etkili olması için komut istemini yeniden başlatın:
setx AZURE_APPCONFIG_ENDPOINT "<endpoint-of-your-app-configuration-store>"PowerShell kullanıyorsanız aşağıdaki komutu çalıştırın:
$Env:AZURE_APPCONFIG_ENDPOINT = "<endpoint-of-your-app-configuration-store>"macOS veya Linux kullanıyorsanız aşağıdaki komutu çalıştırın:
export AZURE_APPCONFIG_ENDPOINT='<endpoint-of-your-app-configuration-store>'Uygulamayı çalıştırın.
node app.jsTarayıcınızı açın ve
localhost:8080adresine gidin. Uygulamanın varsayılan görünümünü görmeniz gerekir.
-
- Kullanıcı kimliğini belirtmek için URL'ye sorgu parametresi olarak ekleyin
userId.localhost:8080/?userId=test@contoso.comadresini ziyaret edin. Hedeflenen kullanıcı olarak belirtildiğindentest@contoso.combeta sayfasını görürsünüz.
- Kullanıcı kimliğini belirtmek için URL'ye sorgu parametresi olarak ekleyin
localhost:8080/?userId=testuser@contoso.comadresini ziyaret edin. Dışlanan kullanıcı olarak belirtildiğindentestuser@contoso.combeta sayfasını göremezsiniz.
Sonraki Adımlar
Özellik filtreleri hakkında daha fazla bilgi edinmek için aşağıdaki belgelere geçin.
JavaScript özellik yönetimi kitaplığının tam özellik çalıştırması için aşağıdaki belgeye geçin.