1.Redis简单介绍
什么是Redis?
Redis是一种NoSQL技术,基于键值对的开源的内存数据存储。
支持五种数据类型的:
属性 | 描述 |
---|---|
string | 字符串 |
hash | 散列 |
list | 列表 |
set | 集合 |
zset | 有序集合 |
Spring Data Redis 提供两个模板(RedisTemplate、StringRedisTemplate):
RedisTemplate:针对键和值都是Object类型数据进行操作
StringRedisTemplate:只针对键和值都是String类型数据进行操作
Serializer:序列化器,当数据存储到内存数据库时,要进行序列化存储
RedisTemplate模板默认使用JdkSerializationRedisSerializer
StringRedisTemplate模板默认使用StringRedisSerializer
2.Redis简单应用开发
例如: 将以下信息存储到Redis中,并分别取出显示:
1、将信息key:hello、value:SpringBoot Redis 存放到Redis db0中;2、插入一个user信息到Redis db0中,查询根据uid取出该user信息显示。
新建一个SpringBoot项目,添加相关依赖:
pom.xml
<!--引入redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!--不依赖 Redis 的异步客户端 lettuce-->
<!--因为starter-data-redis(2.x版本)
会默认使用lettuce客户端,而一般只使用Jedis-->
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--引入Redis的客户端驱动jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!--添加Lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<!--添加freemarker依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
项目结构:
首先我们需要配置一下Redis:
RedisConfig.java
package com.springboot.redisdemo.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Created on 2019/8/19 by Tinchi
**/
@Configuration
public class RedisConfig {
/**
* 将RedisTemplate模板序列化
* 修改为Jackson2JsonRedisSerializer
* @param redisFactory
* @return
*/
@Bean
@SuppressWarnings({"rawtypes","unchecked"})
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisFactory){
RedisTemplate<Object,Object> template=new RedisTemplate<Object,Object>();
template.setConnectionFactory(redisFactory);
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);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
实体类User.java
package com.springboot.redisdemo.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* Created on 2019/8/19 by Tinchi
**/
@Data //LomBok注解,简化getter and setter
@NoArgsConstructor //LomBok注解,无参数的构造函数
@AllArgsConstructor //LomBok注解,全参数的构造函数
//这里需要对实体类进行序列化
public class User implements Serializable {
private static final long serialVersionUID=1L;
String uid;
String username;
String password;
}
数据访问层代码UserRedisDAO.java
package com.springboot.redisdemo.reponsitory;
import com.springboot.redisdemo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
/**
* Created on 2019/8/19 by Tinchi
**/
@Repository //持久化
public class UserRedisDAO {
@Autowired
StringRedisTemplate stringRedisTemplate;
@Resource(name = "stringRedisTemplate") //向定义的对象注入模板对象
ValueOperations<String,String> valOpsStr;
@Autowired
RedisTemplate redisTemplate;
@Resource(name = "redisTemplate") //向定义的对象注入模板对象
ValueOperations<Object,Object> valOps;
public void setStringRedisTemplateDemo(){
valOpsStr.set("hello","SpringBoot Redis");
}
public String getStringByRedis(){
setStringRedisTemplateDemo();
return valOpsStr.get("hello");
}
public void insertUserByRedis(User user){
valOps.set(user.getUid(),user);
}
public User findUserByRedis(String uid){
return (User) valOps.get(uid);
}
}
服务类接口UserService.java
package com.springboot.redisdemo.service;
import com.springboot.redisdemo.entity.User;
/**
* Created on 2019/8/19 by Tinchi
**/
public interface UserService {
String getStrByRedis();
void insertUserByRedis(User user);
User findUserByRedis(String uid);
}
具体实现类UserServiceImpl.java
package com.springboot.redisdemo.service.impl;
import com.springboot.redisdemo.entity.User;
import com.springboot.redisdemo.reponsitory.UserRedisDAO;
import com.springboot.redisdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created on 2019/8/19 by Tinchi
**/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRedisDAO userRedisDAO;
@Override
public String getStrByRedis() {
return userRedisDAO.getStringByRedis();
}
@Override
public void insertUserByRedis(User user) {
userRedisDAO.insertUserByRedis(user);
}
@Override
public User findUserByRedis(String uid) {
return userRedisDAO.findUserByRedis(uid);
}
}
然后是我们的UserController.java
package com.springboot.redisdemo.controller;
import com.springboot.redisdemo.entity.User;
import com.springboot.redisdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
/**
* Created on 2019/8/19 by Tinchi
**/
@RestController
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/getStringByRedis")
//GetMapping组合注解相当于@RequestMapping(value = "getStringByRedis",method = RequestMethod.GET)
//GetMapping是基于Rest风格,在这里全部使用GetMapping是为了方便浏览器进行验证
//根据不同的需求,使用其它Rest风格注解
public ModelAndView getStringByRedis(){
String s=userService.getStrByRedis();
ModelAndView mv=new ModelAndView("redis");
mv.addObject("s",s);
return mv;
}
@GetMapping(value = "/insertUserByRedis")
public ModelAndView insertUserByRedis(String uid,String username,String password){
User user=new User(uid,username,password);
userService.insertUserByRedis(user);
ModelAndView mv=new ModelAndView("insert");
return mv;
}
@GetMapping(value = "/findUserByRedis")
public ModelAndView findUserByRedis(String uid){
User user=userService.findUserByRedis(uid);
ModelAndView mv=new ModelAndView("find");
mv.addObject("user",user);
return mv;
}
}
application.properties文件
##Redis服务器配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.database=0
##连接池配置
spring.redis.jedis.pool.min-idle=5
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.max-active=10
spring.redis.jedis.pool.max-wait=2000
#Redis 连接超时时间,单位毫秒
spring.redis.timeout=1000
## Freemarker 配置
##模版存放路径(默认为 classpath:/templates/)
spring.freemarker.template-loader-path=classpath:/templates/
##是否生成缓存,生成环境建议开启(默认为true)
spring.freemarker.cache=false
##编码
spring.freemarker.charset=UTF-8
##content-type类型(默认为test/html)
spring.freemarker.content-type=text/html
##模板后缀(默认为.ftl)
spring.freemarker.suffix=.ftl
find.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>search!</h1>
学号:${user.uid}<br>
姓名:${user.username}<br>
密码:${user.password}<br>
</body>
</html>
insert.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>插入成功!</h1>
</body>
</html>
redis.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
${s}
</body>
</html>
启动类RedisDemoApplication.java
package com.springboot.redisdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RedisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(RedisDemoApplication.class, args);
}
}
启动Redis服务,运行项目: