Magento 2: how to create your own custom cache type?

This is below some basic structure for create custom cache type,

create one module with,

app/code/Vendor/Cachetype/etc/cache.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Cache/etc/cache.xsd">
    <type name="custom_cache" translate="label,description" instance="Vendor\Cachetype\Model\Cache\Type">
        <label>Custom Cache type</label>
        <description>Custom cache description.</description>
    </type>
</config>

app/code/Vendor/Cachetype/i18n/en_US.csv

"Custom cache description.","Custom cache description."
"cachetype","Cache type"

app/code/Vendor/Cachetype/Model/Cache/Type.php

<?php
namespace Vendor\Cachetype\Model\Cache;

/**
 * System / Cache Management / Cache type "Custom Cache Tag"
 */
class Type extends \Magento\Framework\Cache\Frontend\Decorator\TagScope
{
    /**
     * Cache type code unique among all cache types
     */
    const TYPE_IDENTIFIER = 'custom_cache_tag';

    /**
     * Cache tag used to distinguish the cache type from all other cache
     */
    const CACHE_TAG = 'CUSTOM_CACHE_TAG';

    /**
     * @param \Magento\Framework\App\Cache\Type\FrontendPool $cacheFrontendPool
     */
    public function __construct(\Magento\Framework\App\Cache\Type\FrontendPool $cacheFrontendPool)
    {
        parent::__construct($cacheFrontendPool->get(self::TYPE_IDENTIFIER), self::CACHE_TAG);
    }
}

Thanks.


Would like to edit Rakesh accepted comment, but was rejected....

Anyway here some modifications, additional info to the good answer from Rakesh:

The cache.xml needs to be modfied a little:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="urn:magento:framework:Cache/etc/cache.xsd">
<type name="custom_cache_tag" translate="label,description" instance="Vendor\Cachetype\Model\Cache\Type">
        <label>Custom Cache type</label>
        <description>Custom cache description.</description>
    </type>
 </config>

So the the name must match the cache_tag.

How to use it, look here: Using Magento 2 custom cache in custom module

To use the data (after being cached) you have to unserialize it:

$data = unserialize($this->_cacheType->load($cacheKey));