SpringBoot中如何集成Redis呢?

书欣 SpringBoot 发布时间:2022-09-01 07:43:43 阅读数:17207 1
下文笔者讲述SpringBoot中集成Redis的方法分享,如下所示
我们都知道日常开发中,Redis是我们常用的组件,那么将redis这一优秀的组件应用于SpringBoot中
下文笔者将一一道来,如下所示:
实现思路:
    1.引入redis starter jar包
	2.application中配置相应的属性
	3.编写相应的代码,即可实现redis的操作
例:

SpringBoot引入redis启动器

<!--redis依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置redis的yml信息

#redis配置
  redis:
#  数据库索引
    database: 0
#    服务器地址
    host: 127.0.0.1
#    服务器连接端口
    port: 6379
#    链接密码
    password:
#    链接池
    pool:
#    最大连接数(负值表示没有限制)
      max-active: 8
#      最大阻塞等待时间(负值表示没有限制)
      max-wait: 1
#      最大空闲链接
      max-idle: 8
#      最小空闲链接
      min-idle: 0
#    链接超时时间(毫秒)
    timeout: 0

Redis代码测试

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class RedisAutoTest {

    @Autowired
    private StringredisTemplate stringRedisTemplate;

    @Test
    public void save(){

        stringRedisTemplate.opsForValue().set("rediskey","redisValue");
        Assert.assertEquals("redisValue",stringRedisTemplate.opsForValue().get("redisKey"));
    }
}

Redis存储一个对象

定义一个对象
public class UserInfo implements Serializable{

    private static final long serialVersionUID = 1L;

    private String tel;

    private String nickName;

    @Max(value = 999999,message = "超过最大数值")
    @Min(value = 000000,message = "密码设定不正确")
    private String passWord;

    public UserInfo() {
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "tel='" + tel + '\'' +
                ", nickName='" + nickName + '\'' +
                ", passWord='" + passWord + '\'' +
                '}';
    }

    public UserInfo(String tel, String nickName, String passWord) {
        this.tel = tel;
        this.nickName = nickName;
        this.passWord = passWord;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
}
 
//定义redis系列化接口
public class RedisObjectSerializer implements RedisSerializer<Object> {

    private Converter<Object,byte[]> serializer = new SerializingConverter();
    private Converter<byte[],Object> deserializer = new DeserializingConverter();

    static final byte[] EMPTY_ARRAY = new byte[0];


    @Override
    public byte[] serialize(Object o) throws SerializationException {

        if(o == null){
            return EMPTY_ARRAY;
        }

        try {
        }catch (Exception e){
            return EMPTY_ARRAY;
        }
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if(isEmpty(bytes)){
            return null;
        }
        try {
            return deserializer.convert(bytes);
        }catch (Exception e){
            throw new SerializationException("Can not deserializer",e);
        }

    }

    private boolean isEmpty(byte[] data){

        return (data == null || data.length == 0);
    }
}

//RedisTemplate重新配置
//使用自定义序列化方法
@Configuration
public class RedisConfig {

    @Bean
    JedisConnectionFactory jedisConnectionFactory(){
        return  new JedisConnectionFactory();
    }

    /**
     * 存入对象序列化信息
     * @return
     */
    @Bean
    public RedisTemplate<String,UserInfo> redisSerizlizerObj(){
        RedisTemplate<String,UserInfo> redisTemplate = new RedisTemplate<String,UserInfo>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new RedisObjectSerializer());
        return redisTemplate;
    }
}
 
//例:
 @Autowired
 private RedisTemplate<String,UserInfo> Template;

 @Test
 public void testobjSerializer() throws InterruptedException {
        UserInfo user = new UserInfo("88888","java265user","67777");
        Template.opsForValue().set("User:java265user",user);
        Assert.assertEquals(true,redisTemplate.hasKey("User:java265user"));
    }
	

Redis 存储String

    @Bean
   public RedisTemplate<String,String> redisTemplate(){
        RedisTemplate<String,String> redisTemplate = new StringRedisTemplate();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
 
//例
    @Test
    public void testobj() throws InterruptedException {
        UserInfo user = new UserInfo("1823232323","Java265User","666666");
        ValueOperations<String,UserInfo> operations = redisTemplate.opsForValue();
        operations.set("User:uuuuu",user);
        Thread.sleep(1000);
        operations.set("User:uuuuu",user);
        Thread.sleep(1000);uuuuu
        Assert.assertEquals(true,redisTemplate.hasKey("User:uuuuu"));
        Assert.assertEquals(true,redisTemplate.hasKey("User:uuuuu2"));
    }
以上就是笔者对redis在springBoot集成的简单示例分享
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202209/4289.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者