跳至正文

Cache ​

Introduction ​

Some of the work your application performs can be slow or expensive, such as generating a report that takes several seconds or calling an external API that limits how often you may call it. When that data doesn't change on every request, you may cache it for a while, so later requests read the stored value instead of repeating the work.

Laravel gives you one API for every cache store, so you may start with the in-memory store and move to a database or Redis without changing your application's code. For example, this dashboard handler counts the users at most once every 10 minutes:

go
package dashboard

import (
	"context"
	"fmt"
	"time"

	"go.laravel.com/cache"
	"go.laravel.com/db"
	"go.laravel.com/web"
)

func Show(r *web.Request) *web.Response {
	users, err := cache.Remember(
		r,
		"users:count",
		10*time.Minute,
		func(ctx context.Context) (int, error) {
			return db.Table("users").Count(ctx)
		},
	)
	if err != nil {
		return web.Fail(err)
	}

	return web.Text(fmt.Sprintf("%d users", users))
}

Configuration ​

The CACHE_STORE environment variable selects the default store that the cache package's functions use. Laravel includes several built-in stores:

StoreKeeps values
memoryIn each process's memory, for as long as the process runs. Laravel uses it when CACHE_STORE isn't set.
databaseIn a shared database table, as the database store describes.
redisOn a shared Redis server, as the Redis store describes.
failoverIn the first of several stores that works, as the failover store describes.
discardNowhere. Every read misses, which turns caching off.

New applications use the database store, so every process and server shares cached values, locks, and rate limits:

ini
CACHE_STORE=database

The memory store works well while your application runs on a single server and doesn't need its cache to survive a restart.

Laravel puts CACHE_PREFIX in front of every cache key, so applications that share a store don't read each other's values. The prefix defaults to one built from your application's name, such as laravel_cache_.

The database store ​

The database store keeps cached values in a cache table and atomic locks in a cache_locks table. Your application's create_cache_table migration creates both tables using cache.CreateTables(ctx), so run your migrations before you use the database store:

shell
laravel migrate

If you need to add the cache tables to an existing application, call cache.CreateTables(ctx) inside a migration. It creates both tables using your configured table names (DB_CACHE_TABLE and DB_CACHE_LOCK_TABLE).

By default, the database store uses the database that DATABASE_URL names. You may give the tables other names with DB_CACHE_TABLE and DB_CACHE_LOCK_TABLE. To keep the cache on another database, add the database to cfg.Database.Connections and name it in DB_CACHE_CONNECTION.

Locks live on the same database as cached values. If you'd like to keep locks on another database, add that database to cfg.Database.Connections as well and name it in DB_CACHE_LOCK_CONNECTION:

ini
DB_CACHE_LOCK_CONNECTION=locks

Laravel deletes expired rows about once an hour, so no scheduled task is required. To delete expired rows right away, run cache:prune, passing an optional store name to prune that store instead of the default store:

shell
laravel cache:prune
laravel cache:prune database

说明

Inside a database transaction on the store's database, cache writes join the transaction and roll back if the transaction fails. To keep cache writes independent of your transactions, keep the cache on another database with DB_CACHE_CONNECTION. Locks don't join your transactions, so other requests see a lock as soon as you take it, and a rollback doesn't release it. On SQLite, which allows only one write at a time, locks do join the transaction, because a lock taken outside would wait for the transaction to end.

The Redis store ​

The redis store keeps cached values on the cache Redis connection, which uses database 1 unless you set REDIS_CACHE_DB, and keeps locks on the default connection. It also works with Valkey, including managed Valkey on Laravel Cloud. Once your Redis connections are configured, select the redis store in your .env file:

ini
CACHE_STORE=redis

If you'd like to send values or locks to other Redis connections, name them in REDIS_CACHE_CONNECTION and REDIS_CACHE_LOCK_CONNECTION. Redis expires keys on its own, so no pruning is needed.

警告

Flushing the redis store deletes every key in the cache connection's Redis database, whatever its prefix. Keep the cache connection on a Redis database of its own, as the default configuration does, and keep your own Redis keys in another database.

The failover store ​

If your primary cache store becomes unavailable, every request that reads or writes the cache fails with it. The failover store tries a list of stores in order, and moves on to the next store whenever an operation fails. CACHE_FAILOVER_STORES lists the stores, and defaults to database,memory:

ini
CACHE_STORE=failover
CACHE_FAILOVER_STORES=redis,database

Laravel logs a warning when a store starts failing. Values aren't copied between stores during failover, and atomic locks never fail over: locks always use the first store in the list, so taking a lock fails cleanly while that store is down.

Using several stores ​

Most applications only need the store that CACHE_STORE selects. Sometimes you'll want a second store as well, such as keeping reports in the database while everything else is in Redis. Pass the store's name to cache.Named, which returns a *cache.Cache with a method for each function on this page:

go
reports := cache.Named(r, "database")

total, err := reports.Remember[int](
	r,
	"reports:total",
	time.Hour,
	func(ctx context.Context) (int, error) {
		return db.Table("orders").Count(ctx)
	},
)

cache.Named takes the name of any store in the table of stores, a store of your own, or a store that a package added. Naming a store that doesn't exist, or the database store in an application without a database, panics with a message that says what to fix.

Using the cache ​

The cache package's functions, such as Get and Remember, take a context.Context first and use the cache of the application that the context carries. In a handler, pass the request, r. A queued job, an event listener, or a console command passes the ctx it receives, so the same caching code works in each of them.

If you'd like to use the cache in a goroutine that outlives the request, start the goroutine with r.Background and use the context it gives your function, rather than starting a goroutine of your own with go.

Retrieving items ​

Use cache.Get to retrieve a value as the type you write in brackets. Go can't work out the type from a key, so the brackets are required. Get reports false when the key is missing or expired. You may check whether a key has a value using cache.Has:

go
name, ok, err := cache.Get[string](r, "user:42:name")

cached, err := cache.Has(r, "user:42:name")

To retrieve a value and remove it from the cache in one call, use cache.Pull. For example, an invitation code should work only once:

go
code, ok, err := cache.Pull[string](r, "invitation:42:code")

To fetch several keys in a single call, use cache.Many. It returns a map from each key that has a value to that value, so a missing key is missing from the map:

go
names, err := cache.Many[string](r, "user:1:name", "user:2:name")

Retrieve and store ​

Frequently, you'll want to read a value from the cache and compute it when it's missing. cache.Remember handles both in one call: it returns the cached value if there is one, or calls your function and stores what the function returns for the given duration. For example, this caches the titles of your published posts for an hour:

go
titles, err := cache.Remember(r, "posts:titles", time.Hour, func(ctx context.Context) ([]string, error) {
	return db.Table("posts").WhereNotNull("published_at").Pluck[string](ctx, "title")
})

If your function returns an error, Remember returns the error without caching anything.

If several requests miss the cache at the same time, each of them calls the function. When the work should only run once at a time, coordinate it with an atomic lock.

Stale while revalidate ​

With Remember, the first request that finds an expired value must wait while your function recomputes it. For slow queries or API calls, cache.Flexible avoids that wait by serving the stale value right away while it refreshes the value in the background. Pass how long the value stays fresh, then how long Laravel may serve it in total:

go
posts, err := cache.Flexible(
	r,
	"posts:count",
	5*time.Minute,
	10*time.Minute,
	func(ctx context.Context) (int, error) {
		return db.Table("posts").Count(ctx)
	},
)

For the first 5 minutes, Flexible returns the cached value directly. Between 5 and 10 minutes, it returns the stale value right away and calls your function in a new goroutine to replace it, so the request doesn't wait. After 10 minutes, the value expires, and the next request calls the function before Flexible returns, as Remember does.

Because the background call may finish after the response is sent, it receives a context that the end of the request doesn't cancel. Use that ctx, not the request, for the work inside your function. If the background call fails, Laravel logs the error and keeps serving the stale value.

Storing items ​

Use cache.Put to store a value for a given lifetime. Every cached value needs a lifetime, so give values that rarely change a longer one:

go
err := cache.Put(r, "user:42:name", "Taylor", 10*time.Minute)

err = cache.Put(r, "settings", map[string]string{"theme": "dark"}, 24*time.Hour)

Values are stored as JSON, so you may store anything that encoding/json can encode, and read it back as any type it decodes into. If Get finds a value that doesn't decode as the type you ask for, it returns an error rather than reporting false. By contrast, Remember and Flexible treat such a value as missing and compute it again, so a deploy that changes a struct's fields keeps working.

Use cache.Add to store a value only if the key doesn't have one yet. Laravel checks and writes in one step, and Add reports true if it stored the value and false if another request got there first:

go
started, err := cache.Add(r, "report:monthly:started", true, 10*time.Minute)
if err != nil {
	return web.Fail(err)
}
if started {
	// This request generates the report...
}

Use cache.PutMany to store several keys and values with a shared lifetime, and cache.Touch to give an existing key a new lifetime without rewriting its value. Touch reports whether the key had a value to touch:

go
err := cache.PutMany(r, map[string]any{
	"user:1:name": "Taylor",
	"user:2:name": "Abigail",
}, 10*time.Minute)

touched, err := cache.Touch(r, "report:monthly", 30*time.Minute)

Counters ​

Use cache.IncrementOrAdd to increment an integer counter and return its new value. If the counter doesn't exist yet, IncrementOrAdd creates it with the given amount and lifetime. For example, this counts a client's requests within a one-minute window:

go
hits, err := cache.IncrementOrAdd(r, "hits:"+r.IP(), 1, time.Minute)

cache.Increment adjusts an existing counter without changing its lifetime, and reports false if the key doesn't exist. To decrement a counter, pass a negative amount:

go
visits, ok, err := cache.Increment(r, "visits", 1)

remaining, ok, err := cache.Increment(r, "credits", -1)

Removing items ​

Use cache.Forget to remove a single key, or cache.Flush to clear every value in the store:

go
err := cache.Forget(r, "user:42:name")

err = cache.Flush(r)

You may also flush the default store, or a store by name, using the cache:clear command:

shell
laravel cache:clear
laravel cache:clear database

Each running process keeps a memory store of its own, so cache:clear can't clear the memory store of a running web server. Restart the server to clear a memory store instead.

警告

Flushing ignores CACHE_PREFIX. Flushing a database store empties the entire cache table, including values written by other applications that share that table.

Memoizing reads ​

When a single request reads the same cache key several times, such as a settings value that a middleware, the layout, and the handler each need, cache.Memo avoids the extra round trips to the store. It returns the default store with a memo, which keeps each value it reads in memory for the rest of the current request:

go
settings := cache.Memo(r)

theme, ok, err := settings.Get[string](r, "settings:theme") // Reads the store...
theme, ok, err = settings.Get[string](r, "settings:theme")  // Served from memory...

Every cache.Memo(r) in one request shares the same memo, so a middleware and a handler read the store once between them. To memoize another store, call Memo on it, as in cache.Named(r, "database").Memo(). Writing or forgetting a key clears its memoized value, so the request always sees its own writes.

Atomic locks ​

Atomic locks let you coordinate work so only one process runs a critical section at a time, such as generating an expensive report that several users request at once. Locks on the database and redis stores are shared by every process and server. Locks on the memory store only coordinate within a single process, and the discard store doesn't enforce locks.

Managing locks ​

Call cache.Lock with a lock name and the longest time to hold the lock. Run tries to acquire the lock, runs your function if it succeeds, and releases the lock automatically when the function returns or panics. In this example, a request that arrives while the report is being generated gets a message instead of generating the report a second time:

go
package reports

import (
	"context"
	"time"

	"go.laravel.com/cache"
	"go.laravel.com/web"
)

func Generate(r *web.Request) *web.Response {
	lock := cache.Lock(r, "reports", 10*time.Second)

	acquired, err := lock.Run(r, func(ctx context.Context) error {
		// Generate the report...
		return nil
	})
	if err != nil {
		return web.Fail(err)
	}
	if !acquired {
		return web.Text("The report is already being generated.")
	}

	return web.Text("Report generated.")
}

If the lock is unavailable, you may wait for it with BlockRun, passing how long to wait and the function to run. If the lock can't be taken before the time runs out, BlockRun returns a *cache.LockTimeoutError, which Laravel renders as a 423 Locked response when you pass it to web.Fail:

go
lock := cache.Lock(r, "reports", 10*time.Second)
err := lock.BlockRun(r, 5*time.Second, func(ctx context.Context) error {
	// Lock acquired after waiting up to 5 seconds...
	return nil
})
if err != nil {
	return web.Fail(err)
}

To manage acquisition and release yourself, such as when refreshing a lock or releasing it in another process, call Acquire or Block paired with defer lock.Release(r).

To handle a timeout yourself, such as to ask the user to try again later, check the error with errors.AsType:

go
if _, ok := errors.AsType[*cache.LockTimeoutError](err); ok {
	// Unable to acquire the lock...
}

When protecting a database transaction with a lock, take the lock before you start the transaction, so the lock is released only after the transaction commits.

警告

When acquiring a lock manually with Acquire or Block, release every lock you take with Release (or prefer Run and BlockRun, which release automatically). A lock you don't release stays held until its time runs out, so choose a time longer than the work the lock protects, or refresh the lock as the work progresses.

Managing locks across processes ​

Sometimes you need to take a lock in one process and release it in another, such as taking a lock in a handler and releasing it when a queued job completes. Owner returns the token that identifies the lock's holder, so pass that token to the job:

go
package podcasts

import (
	"time"

	"go.laravel.com/cache"
	"go.laravel.com/queue"
	"go.laravel.com/web"

	"app/jobs"
)

func Process(r *web.Request) *web.Response {
	podcastID, err := r.PathInt("podcast")
	if err != nil {
		return web.Fail(err)
	}

	lock := cache.Lock(r, "processing", 2*time.Minute)

	acquired, err := lock.Acquire(r)
	if err != nil {
		return web.Fail(err)
	}
	if acquired {
		job := jobs.ProcessPodcast{PodcastID: podcastID, Owner: lock.Owner()}

		if _, err := queue.Dispatch(r, job); err != nil {
			return web.Fail(err)
		}
	}

	return web.Back()
}

Inside the job, restore the lock with cache.RestoreLock and the owner token, and release it:

go
// jobs/process_podcast.go
package jobs

import (
	"context"

	"go.laravel.com/cache"
)

type ProcessPodcast struct {
	PodcastID int64
	Owner     string
}

func (j ProcessPodcast) Handle(ctx context.Context) error {
	// Process the podcast...

	_, err := cache.RestoreLock(ctx, "processing", j.Owner).Release(ctx)

	return err
}

To release a lock regardless of its current owner, call ForceRelease:

go
err := cache.RestoreLock(r, "processing", "").ForceRelease(r)

Refreshing locks ​

For long-running work, take a short lock and extend it as the work progresses rather than guessing a long time up front. Refresh extends the lock by its original lifetime from now, and reports false if another owner holds the lock:

go
lock := cache.Lock(r, "yearly-reports", time.Minute)

acquired, err := lock.Acquire(r)
if err != nil {
	return web.Fail(err)
}
if !acquired {
	return web.Text("The reports are already being generated.")
}
defer lock.Release(r)

for month := 1; month <= 12; month++ {
	refreshed, err := lock.Refresh(r)
	if err != nil {
		return web.Fail(err)
	}
	if !refreshed {
		return web.Text("Another process took over the reports.")
	}

	// Generate the month's report...
}

If the lock expired and nobody else took it in the meantime, Refresh takes it again and reports true. Another process could have done some of the work while the lock was free, so refresh before each step rather than after it.

Because a restored lock doesn't know its original lifetime, extend it with RefreshFor instead, such as RefreshFor(ctx, 2*time.Minute).

Logging ​

The cache writes a debug log line for every key it reads, writes, or removes. Each line includes the store's name and the key without CACHE_PREFIX, and leaves out cached values. A line written during a request carries the request's ID, so you may find every key one request read. Show these lines by setting the log level to debug:

ini
LOG_LEVEL=debug
MessageWritten when
cache hitA read finds a value.
cache missedA read finds no value.
cache writtenA value is stored, or a counter changes.
cache forgottenA key is removed.
cache flushedA store is flushed.

Cache stores of your own ​

To store cached values in a backend without a built-in store, such as Memcached, implement the cache.Store interface. Your store only needs to keep bytes by key; Laravel handles JSON encoding, key prefixes, lifetimes, and logging for you:

go
type Store interface {
	Get(ctx context.Context, key string) ([]byte, error)
	Put(ctx context.Context, key string, value []byte, ttl time.Duration) error
	CompareAndSwap(ctx context.Context, key string, old, value []byte, ttl time.Duration) (bool, error)
	Increment(ctx context.Context, key string, by int64) (int64, bool, error)
	Forget(ctx context.Context, key string) error
	Flush(ctx context.Context) error
	AcquireLock(ctx context.Context, name, owner string, ttl time.Duration) (bool, error)
	ReleaseLock(ctx context.Context, name, owner string) (bool, error)
	LockOwner(ctx context.Context, name string) (string, error)
}

Each method's doc comment says what the method must do. CompareAndSwap must check and write in one step, because Add and rate limiting depend on it. If your backend can read and write several keys in one round trip, you may also implement the GetMany and PutMany methods of cache.ManyStore, and cache.Many and cache.PutMany will use them. If your backend keeps expired values until something deletes them, implement the Prune method of cache.PruningStore, and cache:prune will call it.

Register your store by name in the Register option of bootstrap/app.go. In this example, stores is a package of your own that holds the Memcached store:

go
return laravel.Options{
	// ...

	Register: func(app *laravel.Registrar) error {
		app.CacheStore("memcached", stores.NewMemcachedStore(
			app.Env().String("MEMCACHED_ADDR", "127.0.0.1:11211"),
		))

		return nil
	},
}

A package registers a store the same way inside its Register method with app.CacheStore. Next, select the store in your .env file:

ini
CACHE_STORE=memcached

The name works everywhere else a store's name does, such as cache.Named(r, "memcached") or CACHE_FAILOVER_STORES=memcached,memory. A store with the name of a built-in store, such as redis, replaces the built-in store.

Testing ​

Tests use the memory store, as described in configuring your tests. Each test runs with its own application and starts with an empty cache. client.Context() carries the test's application, so you may pass it to any function in the cache package inside your tests:

go
package feature_test

import (
	"testing"

	"go.laravel.com/cache"

	"app/tests"
)

func TestReportsAreCached(t *testing.T) {
	client := tests.New(t)

	client.Get("/reports/monthly").AssertOK()

	cached, err := cache.Has(client.Context(), "report:monthly")
	if err != nil || !cached {
		t.Errorf("the monthly report isn't cached (%v)", err)
	}
}

Cached values expire on the application's clock, so you may test what happens once a value expires using time travel, such as client.Travel(2 * time.Hour), instead of waiting.