我已经记忆了一个对象,并考虑向该变量添加缓存。.如果速度很重要,这是必需的吗?
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>gs-vault-config</artifactId>
<version>1.0</version>
<name>gs-vault-config</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RC2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-vault-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</project>
添加缓存
def user_details
@_user_details ||= user.profiles.includes(":asso_1,:asso_2,:asso_3")
end
答案 0 :(得分:0)
更改您的缓存密钥;使其类似于:users_#{user.id}
;
然后,您需要在用户更新时删除此密钥。
此外,您的user_details方法应类似于:
def user_details
@_user_details ||= Rails.cache.fetch("users_#{user.id}") do
user.profiles.includes(":asso_1,:asso_2,:asso_3")
end
return @_user_details
end
(我不确定您为什么要在@_user_details
中使用它,但我还是像您的示例一样保留它)
您的用户模型应如下所示:
class User < ApplicationRecord
...
after_update { Rails.cache.delete(cache_key) }
def cache_key
"users_#{self.id}"
end
def details
Rails.cache.fetch(cache_key) do
self.profiles.includes(":asso_1,:asso_2,:asso_3")
end
end
end