【发布时间】:2017-07-24 10:33:25
【问题描述】:
我正在尝试用 kotlin 替换一些 java 代码。
比如jpa或者cache。
开始类是:
@EnableAsync
@EnableCaching
@EnableSwagger2
@SpringBootApplication
open class Application
fun main(args: Array<String>) {
SpringApplication.run(Application::class.java)
}
简单的控制器:
@RestController
class CacheController {
@Autowired
private lateinit var cache: CacheService
@PutMapping("{id}")
fun save(@PathVariable id: Long) {
cache.save(id)
}
}
缓存服务:
@Component
@CacheConfig(cacheNames = arrayOf("longCacheManager"), cacheManager = "longCacheManager")
open class CacheService {
@Cacheable(key = "#id")
fun save(id: Long): Long {
return id
}
}
缓存管理器:
@Configuration
open class CacheConfig {
@Autowired
private lateinit var redisConnectionFactory: RedisConnectionFactory
@Bean
@Qualifier("longCacheManager")
open fun longCacheManager(): CacheManager {
val redisTemplate = StringRedisTemplate(redisConnectionFactory)
redisTemplate.valueSerializer = GenericToStringSerializer(Long::class.java)
val cacheManager = RedisCacheManager(redisTemplate)
cacheManager.setUsePrefix(true)
return cacheManager
}
}
可以确认在CacheService的方法save中输入的id参数,但是执行完PutMethod后,redis里面什么都没有。
当我像这样用java编写cacheServie时,redis会保存我想要的。
Java 缓存服务是这样的:
@Component
@CacheConfig(cacheNames = "longCacheManager", cacheManager = "longCacheManager")
public class JavaCacheService {
@Cacheable(key = "#id")
public Long save(Long id) {
return id;
}
}
我也读过这样的文章: https://pathtogeek.com/spring-boot-caching-with-kotlin
我的 SpringBootVersion 是 1.5.3.RELEASE
而 kotlinVersion 是 1.1.3-2
【问题讨论】:
-
如果没有
@EnableCaching,这些注释几乎毫无用处。您链接到的文章中也很清楚地解释了这一点。 -
@EnableCaching 在包含 SpringApplication.run(Application.class); 的启动类中
-
将其添加到您的问题中以确保完整性。
-
为什么您的 Configuration/cacheManager 类是用 Java 编写的,而其他所有东西都是用 Kotlin 编写的?
-
@M.Deinum 已添加
标签: caching spring-boot redis kotlin