Spring-Data-Redis For Spring Boot

上一篇快速了解了结合spring boot 原子操作redis,如果您了解Spring Data Jpa 就知道上述方式比较不友好,不符合敏捷开发的特点.那么今天咱们继续学习单机版redis基于Spring Data Jpa的开发风格.

测试类:

@RedisHash("persons")
data class Person(
        @get:Id
        @javax.persistence.Id
        open var id: String = "",
        @Indexed
        open var name: String = "",
        open var age: Int = 0,
        open var sex: Gender = Gender.MALE
) : Serializable {
    override fun toString(): String {
        return "Person(id='$id', name='$name', age=$age, sex=$sex)"
    }

}

补充: @RedisHash是指定了对象分封map地址的key索引或前缀,@Id存储时默认辅助索引,@Indexed二级索引.

repository:

@NoRepositoryBean
interface UserJpaRepository : PagingAndSortingRepository

为了方便(实现接口)这里我继承了PagingAndSortingRepository而不是子类JpaRepository.

impl:

class UserJpaRepositoryImpl(metadata: EntityInformation, operations: KeyValueOperations) :
        SimpleKeyValueRepository(metadata, operations), UserJpaRepository

 personRepository:

interface PersonRepository : UserJpaRepository

controller:

@RequestMapping("person/set")
    fun setPerson(): Person =
            personRepository.save(Person("t2", "先生", 22, Gender.MALE))

    @RequestMapping("person/get")
    fun getPerson(): Person = personRepository.findById("t2").get()

 

启动入口:

@SpringBootApplication
@EnableRedisRepositories(repositoryBaseClass = UserJpaRepositoryImpl::class)
class ApplicationConfiguration

fun main(args: Array) {
    runApplication(*args)
}

 重复上篇所属步骤即可,习惯于使用data jpa来说这种方式是比较亲切的了,在这几次的测试中发现数据被完整的存储到了redis中,GET方式访问一切回显正常,但具体到数据库可视化时出现了乱码,这对于像我这种轻微强迫症的来说简直不可忍受.接下来就需要深入学习,Key(String)-Value(Object)的序列化问题,尤其是存储Object(NOT STRING).

 

你可能感兴趣的:(Spring-Data-Redis For Spring Boot)