我尝试用kotlin替换一些java代码。
例如jpa或cache。
Start类是:
@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
}
}
CacheService:
@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
}
}
的CacheManager:
@Component
@CacheConfig(cacheNames = "longCacheManager", cacheManager = "longCacheManager")
public class JavaCacheService {
@Cacheable(key = "#id")
public Long save(Long id) {
return id;
}
}
我可以确认在CacheService的方法保存中输入的id的参数,但是在我执行了PutMethod后,redis中没有任何内容。
当我像这样用java编写cacheServie时,redis会保存我想要的东西。
这样的Java缓存服务:
1.5.3.RELEASE
我也读过这样的文章: https://pathtogeek.com/spring-boot-caching-with-kotlin
我的SpringBootVersion是1.1.3-2
和kotlinVersion是 @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id", nullable = false)
private Long id;
答案 0 :(得分:0)
谢谢大家,我通过打开缓存方法来修复它
@Component
@CacheConfig(cacheNames = arrayOf("longCacheManager"), cacheManager = "longCacheManager")
open class CacheService {
@Cacheable(key = "#id.toString()")
open fun save(id: Long): Long {
return id
}
}
Spring使用cglib生成代理。
必须强制继承类和方法。
但kotlin默认为final class
,方法没有关键字open
。