06_Spring Boot 使用NoSQL数据库 Redis

1、pom.xml配置

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

4.0.0

com.linjb

springboot-redis

war

0.0.1-SNAPSHOT

springboot-redis Maven Webapp

http://maven.apache.org

org.springframework.boot

spring-boot-starter-parent

1.3.3.RELEASE

org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-redis

springboot-redis

org.springframework.boot

spring-boot-maven-plugin

 

org.apache.maven.plugins

maven-compiler-plugin

1.8

1.8

UTF-8

 

2、application.properties 配置

# REDIS (RedisProperties)

# Redis数据库索引(默认为0)

spring.redis.database=0

# Redis服务器地址

spring.redis.host=127.0.0.1

# Redis服务器连接端口

spring.redis.port=6379

# Redis服务器连接密码(默认为空)

spring.redis.password=bgsn

# 连接池最大连接数(使用负值表示没有限制)

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=600

 

3、Redis配置类:

package com.linjb.config;

 

import org.springframework.cache.CacheManager;

import org.springframework.cache.annotation.EnableCaching;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.cache.RedisCacheManager;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;

import com.fasterxml.jackson.annotation.PropertyAccessor;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.linjb.model.User;

 

@Configuration

@EnableCaching//开启注解

public class RedisConfig {

 

@Bean

public CacheManager cacheManager(RedisTemplate redisTemplate) {

CacheManager cacheManager = new RedisCacheManager(redisTemplate);

return cacheManager;

/*RedisCacheManager rcm = new RedisCacheManager(redisTemplate);

// 多个缓存的名称,目前只定义了一个

rcm.setCacheNames(Arrays.asList("thisredis"));

//设置缓存默认过期时间(秒)

rcm.setDefaultExpiration(600);

return rcm;*/

}

// 以下两种redisTemplate自由根据场景选择

@Bean

public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {

RedisTemplate template = new RedisTemplate<>();

template.setConnectionFactory(connectionFactory);

 

//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)

Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

 

ObjectMapper mapper = new ObjectMapper();

mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

serializer.setObjectMapper(mapper);

 

template.setValueSerializer(serializer);

//使用StringRedisSerializer来序列化和反序列化redis的key值

template.setKeySerializer(new StringRedisSerializer());

template.afterPropertiesSet();

return template;

}

@Bean

public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {

StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();

stringRedisTemplate.setConnectionFactory(factory);

return stringRedisTemplate;

}

}

 

4、Model层

package com.linjb.model;

 

import java.io.Serializable;

 

public class User implements Serializable{

 

private Integer id;

private String username;

private String pwd;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPwd() {

return pwd;

}

public void setPwd(String pwd) {

this.pwd = pwd;

}

@Override

public String toString() {

return "User [id=" + id + ", username=" + username + ", pwd=" + pwd + "]";

}

}

 

5、Controller 层

package com.linjb.controller;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

import com.linjb.model.User;

 

@RestController

@RequestMapping(value="/users")

public class Controller {

 

@Autowired

private StringRedisTemplate stringRedisTemplate;

@Autowired

private RedisTemplate redisTemplate;

@RequestMapping(value="/saveStr", method=RequestMethod.POST)

public String saveStr(@RequestParam String key,String value){

System.out.println("key:"+key);

System.out.println("value:"+value);

stringRedisTemplate.opsForValue().set(key, value);

return "success";

}

@RequestMapping(value="/getStr", method=RequestMethod.POST)

public String getStr(@RequestParam String key){

System.out.println("key:"+key);

String result=stringRedisTemplate.opsForValue().get(key);

return result;

}

@RequestMapping(value="/saveUser", method=RequestMethod.POST)

public String saveUser(@RequestBody User user){

System.out.println(user);

redisTemplate.opsForValue().set(user.getUsername(),user);

return "success";

}

@RequestMapping(value="/getUser", method=RequestMethod.POST)

public String getUser(@RequestParam String key){

System.out.println("key:"+key);

return redisTemplate.opsForValue().get(key).toString();

}

}

 

6、Application启动类

package com.linjb;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

 

/**

* Spring Boot应用启动类

* @Copyright Copyright (C) 2019 linjb

* @author linjb

* @version 1.0

* @CreateDate 2019年1月31日下午10:25:16

*/

@SpringBootApplication

public class Application /*extends SpringBootServletInitializer*/{

 

public static void main(String[] args) {

SpringApplication.run(Application.class,args);

}

// @Override

// protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {

//

// return builder.sources(Application.class);

// }

}

 

通过上面这段极为简单的测试案例演示了如何通过自动配置的StringRedisTemplate对象进行Redis的读写操作,该对象从命名中就可注意到支持的是String类型。如果有使用过spring-data-redis的开发者一定熟悉RedisTemplate接口,StringRedisTemplate就相当于RedisTemplate的实现。

除了String类型,实战中我们还经常会在Redis中存储对象,这时候我们就会想是否可以使用类似RedisTemplate来初始化并进行操作。但是Spring Boot并支持直接使用,需要我们自己实现RedisSerializer接口来对传入对象进行序列化和反序列化。

你可能感兴趣的:(搬砖之,SpringBoot,专栏)