spring boot连接NoSQL数据库Redis写入和读取数据
Posted zhangphil
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot连接NoSQL数据库Redis写入和读取数据相关的知识,希望对你有一定的参考价值。
既然是连接Redis数据库,首先需要把Redis数据库启动起来。配置启动Redis详情:
然后,
(1)创建一个maven的spring项目,在pom.xml添加相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
(2)在resources下的application.properties里面配置连接Redis数据库的参数信息:
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database=0
# Redis默认密码为空
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.timeout=60000
(3)编写项目所需的各个模块、类。
spring boot连接Redis所需的数据库配置类:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
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;
import java.time.Duration;
@Configuration
@EnableAutoConfiguration
public class MyRedisAutoConfiguration
@Value("$spring.redis.host")
private String host;
@Value("$spring.redis.database")
private Integer database;
@Value("$spring.redis.port")
private Integer port;
@Value("$spring.redis.jedis.pool.max-active")
private int maxActive;
@Value("$spring.redis.jedis.pool.max-wait")
private int maxWait;
//@Value("$spring.redis.timeout")
//private int timeOut;
@Bean
public RedisTemplate<String, Object> MY_REDIS_TEMPLATE(RedisConnectionFactory connectionFactory)
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
@Bean
public RedisConnectionFactory redisConnectionFactory()
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(port);
redisStandaloneConfiguration.setDatabase(database);
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxWait(Duration.ofMillis(maxWait));
poolConfig.setMaxTotal(maxActive);
JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder().usePooling().poolConfig(poolConfig);
JedisClientConfiguration jedisClientConfiguration = jpcb.build();
return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
数据库存取的数据实体类,即打算往Redis数据库存入的结构化数据对象,本例是一个person类:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person
private String name;
private String city;
写一个通过RedisTemplat读写操作Redis数据库的服务类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
@Service
public class MyRedisService
@Autowired
RedisTemplate MY_REDIS_TEMPLATE; //注意,这里的变量名需要和MyRedisAutoConfiguration里面的RedisTemplate实现函数名相同。
public boolean setPerson(String key, Person value)
boolean result = false;
try
MY_REDIS_TEMPLATE.opsForValue().set(key, value);
result = true;
catch (Exception e)
e.printStackTrace();
return result;
public Person getPerson(String key)
return (Person) MY_REDIS_TEMPLATE.opsForValue().get(key);
public HashMap<String, Person> getAllPerson()
Set<Object> set = MY_REDIS_TEMPLATE.keys("*");
Iterator iterator = set.iterator();
HashMap<String, Person> map = new HashMap<>();
while (iterator.hasNext())
String k = (String) iterator.next();
Person p = (Person) MY_REDIS_TEMPLATE.opsForValue().get(k);
map.put(k, p);
return map;
对外暴露的接口控制器controller:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.UUID;
@RestController
public class PersonController
@Autowired
private MyRedisService redisService;
@GetMapping("/add/name")
public String add(@PathVariable("name") String name)
Person person = new Person(name, "Chengdu");
try
redisService.setPerson(UUID.randomUUID() + "", person);
System.out.println("写入Redis:" + person);
catch (Exception e)
e.printStackTrace();
return person.toString();
@GetMapping("/person/id")
public Person getById(@PathVariable("id") String id)
Person p = redisService.getPerson(id);
System.out.println("读取" + p);
return p;
@GetMapping("/all")
public HashMap<String, Person> getAll()
return redisService.getAllPerson();
剩下的就是一个简单的application:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringRedisApplication
public static void main(String[] args)
SpringApplication.run(SpringRedisApplication.class, args);
(4)以上代码完成后,开始运行spring boot程序。在浏览器输入
如果一切正常,浏览器会返回输出显示:
Person(name=fly, city=Chengdu)
在浏览器输入http://localhost:8080/all
浏览器返回:
"85505b27-f798-42c8-9713-c523e2a63aaa":"name":"fly","city":"Chengdu"
可知此时的Redis数据库里面,key是85505b27-f798-42c8-9713-c523e2a63aaa的数据条目对应的值为:
"name":"fly","city":"Chengdu"
此时,如果在浏览器里面输入http://localhost:8080/person/85505b27-f798-42c8-9713-c523e2a63aaa
浏览器返回输出:
用Another Redis Desktop Manager查看此时的数据数据存储:
再用另外一个Redis GUI工具redis-gui查看:
以上是关于spring boot连接NoSQL数据库Redis写入和读取数据的主要内容,如果未能解决你的问题,请参考以下文章
使用 Spring Boot 与 SQL 数据库连接的服务器发送事件
spring boot基于NoSQL数据库Redis发送接收存储消息