So you want to use Redis Cache with Salesforce Commerce Cloud!!
Roll Your Own Architecture (taken from Explore Headless Architecture and Implementation Roles | Salesforce)

So you want to use Redis Cache with Salesforce Commerce Cloud!!

Salesforce Commerce Cloud Headless and composable implementations empower businesses to craft unique and unparalleled customer experiences, all driven by a robust back-end eCommerce platform. By decoupling the front-end presentation layer from the back-end engine via APIs, companies gain the flexibility to develop dynamic commerce capabilities. This approach enables the delivery of API-driven experiences across CMS, DXP, applications, devices, or custom front-ends.

We all know this, but what about caching.

Indeed, caching in Salesforce Commerce Cloud extends beyond simply adding <iscache> tags to templates. It encompasses multiple layers, particularly in a B2C context, including the shopper's browser, the CDN, the web server, the application server, and the storage layer (database). An effective caching strategy involves elevating the cached content across these layers to optimize performance.

  • The shopper’s browser
  • The CDN
  • The web server
  • The application server
  • The storage layer (e.g., the database)

An effective caching strategy aims to position cached content as near to the user as feasible. The necessity to navigate through multiple layers can result in slower response times and reduced throughput for the website.

Hey its Headless/Composable correct can I not use Redis Cache?

Why, thank you for asking, yes you can! You can do it for both SFCC and for PWA-Kit as well.

Here is how you do it,

SFCC Redis Caching,

Integrating Redis cache with Salesforce Commerce Cloud (SFCC) involves several steps and considerations. While SFCC does not natively support Redis, you can use custom caching mechanisms to achieve similar functionality. Here’s a detailed guide on how to integrate Redis cache with SFCC:

1. Understanding Custom Caches in SFCC

SFCC allows the use of custom caches to store data that is computationally expensive, slow to retrieve, or frequently accessed. Custom caches are defined within a JSON file in a custom cartridge and managed using the dw.system.CacheMgr and dw.system.Cache classes from the B2C Commerce script API.

2. Setting Up Redis

First, you need to set up a Redis server. This can be done on-premises or using a cloud service like AWS ElastiCache, Azure Redis Cache, or Redis Labs.

3. Creating a Custom Cartridge

Create a custom cartridge in SFCC to manage the integration with Redis. This cartridge will contain the logic for interacting with the Redis server.

4. Defining Custom Caches

Define custom caches in a JSON file within your custom cartridge. Here’s an example of how to define a custom cache:

{

"caches": [

{

"id": "myCustomCache",

"maxEntries": 1000,

"expiration": 3600

}

]

}

5. Implementing Redis Integration

Use the dw.system.CacheMgr and dw.system.Cache classes to interact with the custom cache. Additionally, you will need to use a Redis client library to interact with the Redis server. Here’s an example of how to implement this in a script:

const CacheMgr = require('dw/system/CacheMgr');

const Cache = require('dw/system/Cache');

const redis = require('redis');

// Create a Redis client

const client = redis.createClient({

host: 'your-redis-host',

port: 6379,

password: 'your-redis-password'

});

// Function to get data from Redis

function getFromRedis(key) {

return new Promise((resolve, reject) => {

client.get(key, (err, data) => {

if (err) {

reject(err);

} else {

resolve(data);

}

});

});

}

// Function to set data in Redis

function setInRedis(key, value, expiration) {

return new Promise((resolve, reject) => {

client.set(key, value, 'EX', expiration, (err) => {

if (err) {

reject(err);

} else {

resolve();

}

});

});

}

// Example function to use custom cache with Redis

function getCachedData(key) {

const cache = CacheMgr.getCache('myCustomCache');

let data = cache.get(key);

if (!data) {

// If data is not in custom cache, check Redis

data = getFromRedis(key).then((redisData) => {

if (redisData) {

// Store data in custom cache

cache.put(key, redisData);

return redisData;

} else {

// Fetch data from the original source, e.g., a database

const newData = fetchDataFromSource(key);

// Store data in Redis and custom cache

setInRedis(key, newData, 3600);

cache.put(key, newData);

return newData;

}

});

}

return data;

}

// Example function to fetch data from the original source

function fetchDataFromSource(key) {

// Implement your data fetching logic here

return 'fetched data';

}

6. Managing Cache Expiration

Ensure that you manage cache expiration appropriately. The setInRedis function in the example above sets an expiration time for the Redis cache. Similarly, you can set expiration times for custom caches in SFCC.

7. Testing and Optimization

Thoroughly test the integration to ensure that data is being cached and retrieved correctly. Monitor the performance and optimize the cache settings as needed.

Now what about with PWA-KIT

Step 1: Set Up Redis

First, ensure that you have a Redis instance running. You can use a managed Redis service like AWS ElastiCache, Azure Redis Cache, or set up your own Redis server.

Step 2: Install Redis Client

Install a Redis client for Node.js in your PWA Kit project. You can use ioredis or redis npm package. Here’s how to install ioredis:

npm install ioredis

Step 3: Configure Redis Client

Create a configuration file for your Redis client. For example, you can create a redisClient.js file:

const Redis = require('ioredis');

const redis = new Redis({

host: 'your-redis-host',

port: 6379, // default Redis port

password: 'your-redis-password' // if applicable

});

module.exports = redis;

Step 4: Implement Caching Logic

Integrate the Redis client into your caching logic. You can adapt the existing caching mechanisms in SFCC to use Redis. Here’s an example of how you might modify the PersistentCache class to use Redis:

const redis = require('./redisClient');

class PersistentCache {

constructor(options) {

this.useLocalCache = options.useLocalCache;

this.namespace = options.namespace || 'default';

}

async get({ key, namespace }) {

const cacheKey = ${namespace}:${key};

const data = await redis.get(cacheKey);

if (data) {

return {

found: true,

key,

namespace,

data: Buffer.from(data, 'base64')

};

}

return { found: false, key, namespace };

}

async put({ key, namespace, data, expiration }) {

const cacheKey = ${namespace}:${key};

await redis.set(cacheKey, data.toString('base64'), 'EX', expiration);

}

async delete({ key, namespace }) {

const cacheKey = ${namespace}:${key};

await redis.del(cacheKey);

}

}

module.exports = PersistentCache;

Step 5: Use the Cache in Your Application

Use the PersistentCache class in your application to cache responses. Here’s an example of how you might use it in an Express route:

const express = require('express');

const PersistentCache = require('./PersistentCache');

const app = express();

const cache = new PersistentCache({ useLocalCache: false, namespace: 'myApp' });

app.get('/some-route', async (req, res) => {

const cacheKey = 'someUniqueKey';

const cachedResponse = await cache.get({ key: cacheKey, namespace: 'myApp' });

if (cachedResponse.found) {

res.send(cachedResponse.data);

} else {

// Generate the response

const responseData = 'Hello, World!';

await cache.put({ key: cacheKey, namespace: 'myApp', data: Buffer.from(responseData), expiration: 600 });

res.send(responseData);

}

});

app.listen(3000, () => {

console.log('Server is running on port 3000');

});

In the End,

By following these steps, you can integrate Redis cache with Salesforce Commerce Cloud. This setup will help you store and retrieve cached data efficiently, improving the performance of your application. If you need more specific details or run into issues, please refer to the Redis and SFCC documentation or reach out for further assistance.


Adrian Corral

Product Manager | Integration Architect | Strategic Business Developer | Innovation | B2B & B2C eCommerce

6 个月

I spy with my eye a tax service ??

要查看或添加评论,请登录

Abhijeet Mishra的更多文章

社区洞察

其他会员也浏览了