从零开始学习SpringBoot——06.使用redis

文章目录

    • 1.文件组织结构
    • 2.redis的连接命令
    • 3.可能会出现的报错
    • 4.建立Maven项目,写pom文件
    • 5.添加 redis 的配置文件
    • 6.redis的配置类
    • 7.对象的序列化接口
    • 8.测试类
    • 9.运行结果

1.文件组织结构

从零开始学习SpringBoot——06.使用redis_第1张图片

2.redis的连接命令

  • redis后台服务器的开启命令:./redis-server redis.conf (在redis-server redis.conf安装目录下运行)

  • redis后台服务器的关闭命令:./redis-cli shutdown (在redis-cli安装目录下运行)

  • redis指定ip和密码连接: ./redis-cli -h 192.168.154.128 -p 6379 -a 123456

3.可能会出现的报错

报错:redis.clients.jedis.exceptions.JedisConnectionException: Failed connecting to host ********

解决办法:修改redis服务器的配置文件
从零开始学习SpringBoot——06.使用redis_第2张图片

4.建立Maven项目,写pom文件


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0modelVersion>

	<groupId>com.playergroupId>
	<artifactId>springboot-redis-standaloneartifactId>
	<version>0.0.1-SNAPSHOTversion>
	<packaging>jarpackaging>

	<name>springboot-redis-standalonename>
	<description>Demo project for Spring Bootdescription>

	<parent>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-parentartifactId>
		<version>2.4.6version>
		<relativePath/> 
	parent>

	<properties>
		<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
		<java.version>11java.version>
	properties>

	<dependencies>

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-data-redisartifactId>
		dependency>

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
		dependency>

		<dependency>
			<groupId>redis.clientsgroupId>
			<artifactId>jedisartifactId>
		dependency>
		<dependency>
			<groupId>junitgroupId>
			<artifactId>junitartifactId>
		dependency>
	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
			plugin>
		plugins>
	build>


project>

5.添加 redis 的配置文件

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0

6.redis的配置类

package com.player.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {
	
	@Value("${spring.redis.database}")
	private int database;
	
	@Value("${spring.redis.host}")
	private String host;
	
	@Value("${spring.redis.port}")
	private int port;
	
	@Value("${spring.redis.timeout}")
	private int timeout;
	
	@Value("${spring.redis.pool.max-idle}")
	private int maxidle;
	
	@Value("${spring.redis.pool.min-idle}")
	private int minidle;
	
	@Value("${spring.redis.pool.max-active}")
	private int maxActive;
	
	@Value("${spring.redis.pool.max-wait}")
	private long maxWait;

    @Value("${spring.redis.password}")
    private String password;
	
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
    	JedisPoolConfig config = new JedisPoolConfig(); 
//    	最大空闲连接数, 默认8个
        config.setMaxIdle(maxidle);
//      最小空闲连接数, 默认0
        config.setMinIdle(minidle);
//      最大连接数, 默认8个
        config.setMaxTotal(maxActive);
//      获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
        config.setMaxWaitMillis(maxWait);
        
    	JedisConnectionFactory factory = new JedisConnectionFactory();
    	factory.setDatabase(database);
        factory.setHostName(host);
        factory.setPort(port);
        factory.setTimeout(timeout);
        factory.setPoolConfig(config);
        factory.setPassword(password);
        return factory;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
	@Bean
    public RedisTemplate<String, ?> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, ?> template = new RedisTemplate();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        return template;
    }


}

7.对象的序列化接口

package com.player.config;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

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];

  public Object deserialize(byte[] bytes) {
    if (isEmpty(bytes)) {
      return null;
    }

    try {
      return deserializer.convert(bytes);
    } catch (Exception ex) {
      throw new SerializationException("Cannot deserialize", ex);
    }
  }

  public byte[] serialize(Object object) {
    if (object == null) {
      return EMPTY_ARRAY;
    }

    try {
      return serializer.convert(object);
    } catch (Exception ex) {
      return EMPTY_ARRAY;
    }
  }

  private boolean isEmpty(byte[] data) {
    return (data == null || data.length == 0);
  }
}

8.测试类

package com.player;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Assert;
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.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import com.player.entity.User;


@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRedisApplicationTests {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private RedisTemplate<String, User> redisTemplate;
	
	@Autowired
	private RedisTemplate<String, List<User>> rt;
	
	
	@Autowired
	private RedisTemplate<String, List<Map<String,Object>>> rm;

	@Test
	public void test() throws Exception {

		// 保存字符串
		stringRedisTemplate.opsForValue().set("url", "www.baidu.com");
		Assert.assertEquals("www.baidu.com", stringRedisTemplate.opsForValue().get("url"));

		// 保存对象
		User user = new User("C++", 40);
		redisTemplate.opsForValue().set(user.getUsername(), user);

		user = new User("Java", 30);
		redisTemplate.opsForValue().set(user.getUsername(), user);

		user = new User("Python", 20);
		redisTemplate.opsForValue().set(user.getUsername(), user);

		Assert.assertEquals(20, redisTemplate.opsForValue().get("Python").getAge());
		Assert.assertEquals(30, redisTemplate.opsForValue().get("Java").getAge());
		Assert.assertEquals(40, redisTemplate.opsForValue().get("C++").getAge());

	}
	
	@Test
	public void test1() throws Exception{
		List<User> us = new ArrayList<>();
		User u1 = new User("rs1", 21);
		User u2 = new User("rs2", 22);
		User u3 = new User("rs3", 23);
		us.add(u1);
		us.add(u2);
		us.add(u3);
		rt.opsForValue().set("key_ul", us);
		System.out.println("放入缓存》。。。。。。。。。。。。。。。。。。。");
		System.out.println("=============================");
		List<User> redisList = rt.opsForValue().get("key_ul");
		System.out.println("redisList="+redisList);
	}
	
	@Test
	public void test2() throws Exception{
		List<Map<String,Object>> ms = new ArrayList<>();
		Map<String,Object> map = new HashMap<>();
		map.put("name", "rs");
		map.put("age", 20);
		
		Map<String,Object> map1 = new HashMap<>();
		map1.put("name", "rs1");
		map1.put("age", 21);
		
		Map<String,Object> map2 = new HashMap<>();
		map2.put("name", "rs2");
		map2.put("age", 22);
		
		ms.add(map);
		ms.add(map1);
		ms.add(map2);
		rm.opsForValue().set("key_ml", ms);
		System.out.println("放入缓存》。。。。。。。。。。。。。。。。。。。");
		System.out.println("=============================");
		List<Map<String,Object>> mls = rm.opsForValue().get("key_ml");
		System.out.println("mls="+mls);
	}

}

9.运行结果

从零开始学习SpringBoot——06.使用redis_第3张图片

你可能感兴趣的:(spring,boot,springboot)