API 如何有效缓存,使用 Angular CLI 在 Angular 5 中使用 Service Worker [英] How API is getting cached effectively, Using Service worker in Angular 5 using Angular CLI

查看:25
本文介绍了API 如何有效缓存,使用 Angular CLI 在 Angular 5 中使用 Service Worker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Service Worker 的新手.我只想知道 Service Worker 如何处理数据变化.

例如,我已经配置了我的数据组并将 strategy 设置为 "performance" 以便 Service Worker 始终首先查看缓存.这意味着任何时候,hit service worker 中的注册 URL 都会首先查看缓存.假设响应有一些变化(数据库中的数据发生了变化),响应会更新还是仍然会从缓存中获取.

我在网上搜索了很多我没有得到满意的答案.如果有人可以请帮助我

配置

"数据组":[{"name":"task-user-api","urls":["/tasks","/users"],缓存配置":{策略":性能",最大尺寸":20,"maxAge":"1h","超时":"5s"}}]

解决方案

经过几个小时的搜索,我找到了答案,有不同类型的缓存可用

一个.网络或缓存 - 提供来自网络的内容,但如果来自网络的答案未按时到达,则包含超时以回退到缓存数据.

B.仅缓存 -- 在 Service Worker 安装过程中添加静态内容,无论网络是否可用,都使用缓存来检索它.

c.缓存和更新 -- 提供缓存中的内容,并执行网络请求以获取新数据以更新缓存条目,确保用户下次访问页面时他们将看到最新内容.

d.缓存更新和刷新 -- 提供缓存中的内容,但同时执行网络请求以更新缓存条目并通知 UI 最新的内容.

e.嵌入式后备 -- 嵌入后备内容并在请求资源失败时提供它.

您可以从

Am new to service worker. I just want to know how the service worker handling the Data changes.

For example, I have configured my data group in and set strategy to "performance" so that Service worker will always look first in Cache. That means any time the Registered URL in hit service worker will look in the cache first. Suppose the response has some changes ( data in database got changed ) will the response will update or still, it will take from the cache.

I searched quite a bit in net I didn't get a satisfying answer. if anybody can please help me

Cofiguration

"dataGroups":[
 {
   "name":"task-user-api",
   "urls":["/tasks","/users"],
   "cacheConfig":
    {
      "strategy" : "performance",
      "maxSize":20,
      "maxAge":"1h",
      "timeout":"5s"
    }
  }
]

解决方案

After few more hours of search, I found the answer to it, There are different type of caching available

a. Network or cache - Serve content from the network but include a timeout to fall back to cached data if the answer from the network doesn’t arrive on time.

b. Cache only -- Add static content during the installation of the service worker and use the cache to retrieve it whether the network is available or not.

c. Cache and Update -- Serve the content from the cache and also perform a network request to get fresh data to update the cache entry ensuring next time the user visits the page they will see up to date content.

d. Cache update and refresh -- Serve the content from the cache but at the same time, perform a network request to update the cache entry and inform the UI about new up to date content.

e. Embedded fallback -- Embed fallback content and serve it in case of a failure while requesting resources.

You can read more and get code for each implimentation from here

Complete code to get the Caching and alert on UI if anything changed on server

Service-worker.js

var cacheName = 'cache-update-and-refresh';;
var cacheFiles = [
    './',
    // list all the assests you want to list
]



self.addEventListener('install', function (e) {
    console.log("[serviceWorker] installed")

    e.waitUntil(
        caches.open('default-cache').then(function (cache) {
            return cache.addAll(cacheFiles)
        }).then(function () {
            return self.skipWaiting();
        }));
    console.log("[serviceWorker] Cached")
})

self.addEventListener('activate', (event) => {
    console.info('Event: Activate');
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.map((cache) => {
                    if (cache !== cacheName) {     //cacheName = 'cache-v1'
                        return caches.delete(cache); //Deleting the cache
                    }
                })
            );
        })
    );
});

self.addEventListener('fetch', function (event) {
    event.respondWith(
        caches.match(event.request).then(function (response) {
            return response || fetch(event.request);
        })
    );
    event.waitUntil(
        update(event.request)
            .then(function (response) {
                caches.open(cacheName).then(function (cache) {
                    caches.match(event.request).then(function (cacheresponse) {
                            if (cacheresponse.headers.get("ETag") !== response.headers.get("ETag")) {
                                console.log('[ServiceWorker]' + response.url + ' - Cache' + cacheresponse.headers.get("ETag") + "- real" + response.headers.get("ETag"));
                                cache.put(event.request, response.clone()).then(function () {
                                    refresh(event.request, response);
                                });
                            }
                    });
                });
            })
    )
});

function fromCache(request) {
    return caches.open(cacheName).then(function (cache) {
        return cache.match(request);
    });
}

function update(request) {
    return caches.open(cacheName).then(function (cache) {
        return fetch(request).then(function (response) {
            return response;
        });
    });
}


function refresh(req, response) {
    return self.clients.matchAll().then(function (clients) {
        clients.forEach(function (client) {
            var message = {
                type: 'refresh',
                url: response,
                eTag: response.headers.get('ETag')
            };
            client.postMessage(JSON.stringify(message));
        });
    });
}

in Index.html

if ('serviceWorker' in navigator) {
    navigator.serviceWorker
        .register('./service-worker.js', { scope: './' })
        .then(function (registration) {
            console.log("Service worker registered", registration)
        })
        .catch(function (err) {
            console.log("Service Worker Failes to Register", err)
        })

    navigator.serviceWorker.addEventListener('message', function (event) {
        document.getElementById("cache-generic-msg").style.display = "block";
        console.log("Got reply from service worker: " + event.data);
    });

} 

Sequence diagram

这篇关于API 如何有效缓存,使用 Angular CLI 在 Angular 5 中使用 Service Worker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆