spring data redis-1

来源:互联网 发布:郑州网络诈骗被一窝端 编辑:程序博客网 时间:2024/06/05 16:22

Spring Data Redis

写在前面的话

想要快速集成redis这种kv型缓存数据库到项目中,完成后端代码的正常crud操作以及服务器中服务的启动关闭

服务器中

这里使用docker,docker是一种容器技术用来运行极其紧密的服务,服务生存在镜像中,镜像运行时成为容器,容载服务运行,镜像的存储运用了联合文件系统的思想,将最终需要依赖的文件镜像分层,使得在使用类似的镜像时能够重用数据,但是对于上层镜像来说,下层镜像是不可修改的,只能通过覆盖文件的方式达到修改的操作,容器运行时是严格按照makefile的规范的,容器内部映射端口的规则为通过-p参数去指定映射指定参数端口到容器内部

获取镜像

docker pull docker.io/redis

运行镜像

docker run --name redis -v /linyi/docker/redis:/data -p 6379:6379 -d  redis redis-server --appendonly yes

–name redis ,指定容器名称

-v /linyi/docker/redis:/data ,指定数据卷存放位置

-p 6379:6379 ,映射端口,hostPort:containerPort

-d ,后台方式启动

redis-server :服务端启动

–appendonly yes 持久化支持

停止容器

docker stop container_id

后台中

这里使用spring boot,spring boot基于spring 4.0,内置很多依赖管理,在使用spring全家桶时是非常适合的

pom.xml中

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency>    <groupId>org.projectlombok</groupId>    <artifactId>lombok</artifactId>    <optional>true</optional></dependency>

application.properties/application.yml中

spring.redis.host=hostnamespring.redis.port=6379

启动类中-XxxApplication

@EnableRedisRepositories

entity–PersonRedis、Address、Gender

Repository其实是基于实体的,PersonRedis是与redis直接关联的对象,Address是为了测试属性集合中存放对象,Gender是为了测试枚举类

package com.linyi.spring_data_redis_repository_demo.entity;public enum Gender {    BOY,GIRL}、、、、、、、、、、、、、、、、、、、、、、package com.linyi.spring_data_redis_repository_demo.entity;import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;@Data@AllArgsConstructor@Builderpublic class Address {    private String id;    private String name;}、、、、、、、、、、、、、、、、、、、、、、package com.linyi.spring_data_redis_repository_demo.entity;import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor;import org.springframework.data.annotation.Id;import org.springframework.data.annotation.Reference;import org.springframework.data.redis.core.RedisHash;import org.springframework.data.redis.core.index.Indexed;import java.util.List;@RedisHash("persons") //prefix@Data@Builder@NoArgsConstructor@AllArgsConstructorpublic class PersonRedis {    @Id private String id; //it will gennerate the uuid value to id when it's null ,so allow id is null    @Indexed private String secondaryId; //the seconde prefix ,if add this there will become persons:secondaryId,and if below has more secondary index ,it will be ordered like `:theNextName`    @Reference private List<PersonRedis> others;    private String name;    private Gender gender;}

repository-PersonRedisRepository:

package com.linyi.spring_data_redis_repository_demo.repository;import com.linyi.spring_data_redis_repository_demo.entity.PersonRedis;import org.springframework.data.repository.CrudRepository;import org.springframework.stereotype.Repository;@Repositorypublic interface PersonRedisRepository  extends CrudRepository<PersonRedis,String>{    Page<PersonRedis> findAll(Pageable page);}

test-PersonRedisTest:

package com.linyi.spring_data_redis_repository_demo;import com.linyi.spring_data_redis_repository_demo.entity.Gender;import com.linyi.spring_data_redis_repository_demo.entity.PersonRedis;import com.linyi.spring_data_redis_repository_demo.repository.PersonRedisRepository;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.UUID;@RunWith(SpringRunner.class)@SpringBootTestpublic class PersonRedisTests {    @Autowired    PersonRedisRepository redisRepository;    List<PersonRedis> savedData = new ArrayList<>();    /**the result of runsave = PersonRedis(id=12a72b27-837e-4c86-8f05-f8ee58e2efe3, secondaryId=secondaryId, others=null, name=linyi, gender=BOY)save1 = PersonRedis(id=dd015ebc-7fa6-4f84-a89d-edb59dc4d943, secondaryId=secondaryId, others=[PersonRedis(id=12a72b27-837e-4c86-8f05-f8ee58e2efe3, secondaryId=secondaryId, others=null, name=linyi, gender=BOY)], name=linyi, gender=BOY)     * */    @Test    public void testAdd() {        // object can thought call builder to get a builder data object,but last data will be losed ,so sometimes you just before in use it to use it's builder object        PersonRedis.PersonRedisBuilder personRedisBuilder = PersonRedis.builder().gender(Gender.BOY).name("linyi").secondaryId("secondaryId");        PersonRedis save = redisRepository.save(personRedisBuilder.build());        System.out.println("save = " + save);        PersonRedis save1 = redisRepository.save(personRedisBuilder.others(Arrays.asList(save)).build()); //so if want to save some reference data list ,you should to make sure that there are already exit id-value in reids,so you can do better do it like before that operation is to save data        // redis can't cascade add data,but when  find data it will use cascade ,so you must sure that data is already exits        System.out.println("save1 = " + save1);    }    @Test    public void testFindAll() {        Iterable<PersonRedis> all = redisRepository.findAll();        all.forEach(t->{            System.out.println(t.toString());        });    }    /**run this method to reset current test result and you cat test against ,it will delete all data in redis with Person.RedisHash.value-value ,so must be careful*/    @Test    public void testRemoveAll() {        redisRepository.deleteAll();    }    @Test    public void testFindOne() {        PersonRedis one = redisRepository.findOne("dd015ebc-7fa6-4f84-a89d-edb59dc4d943");        System.out.println("one = " + one);    }        @Test    public void testUpdateOne() {        PersonRedis one = redisRepository.findOne("dd015ebc-7fa6-4f84-a89d-edb59dc4d943");        one.setName("updateName");        PersonRedis update = redisRepository.save(one);        System.out.println("update = " + update);    }/** exists = truenotExists = false* */    @Test    public void testExist() {        boolean exists = redisRepository.exists("dd015ebc-7fa6-4f84-a89d-edb59dc4d943");        System.out.println("exists = " + exists);        boolean notExists = redisRepository.exists("dd015ebc-7fa6-4f84-a89d-edb59dc4d94312123");        System.out.println("notExists = " + notExists);    }}    @Test    public void testPageFind(){        System.out.println("findAllPage================================>");        PageRequest pageRequest = new PageRequest(0, 4);        Page<PersonRedis> all = redisRepository.findAll(pageRequest);        all.iterator().forEachRemaining(t->{            System.out.println(t);        });        System.out.println("findAllPage================================>");    }

写在后面的话

redis功能很强大,spring data redis有很多个例子,但是这里只是介绍一点点repository相关的,从redis的角度讲,五种数据类型,String/Set/ZSet/Hash/List,repository只是用到了Hash,但是也是足够的面对一些小问题的

原创粉丝点击