Springboot整合Redis入门(一)
Redis是什么不必多说了,既然都要用到redis,说明对其也有一些了解了。这篇文章重点在于最快速度上手redis,做一个能看见效果的小demo出来。
一. Redis安装(Docker安装)
/*查找redis镜像*/
docker search redis
/*拉取镜像,这里是最新的官方镜像*/
docker pull redis
/*运行,这里注意一下服务器的安全组是否开放了6379端口*/
docker run -p 6379:6379 -d --name my-redis redis:latest redis-server
这里只是Linux安装Redis,其他系统的安装自行去网上找找看,都有的,这里不做详细说明。
二. SpringBoot项目引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
三. 配置文件中配置Redis
##yaml文件需注意一下缩进的格式
spring
redis:
host: 47.98.135.2xx #这是部署redis的服务器地址
port: 6379
password: #密码没有的话,就不用填
四.RedisConfig类[可选](可写可不写)
package com.braisedpanda.my.blog.web.config.redis;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* redis配置类
* @program: springbootdemo
* @Date: 2019/1/25 15:20
* @Author: Mr.Zheng
* @Description:
*/
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig extends CachingConfigurerSupport {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
//使用fastjson序列化
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
这个RedisConfig类可有可无的,没有这个类,并不影响redis的使用。使用这个类之后,存储的内容是容易阅读的JSON格式,存储的对象是JSONObject。
下面看下使用与否的对比:
** 没有加入RedisConfig:*
** 使用了RedisConfig:*
五.demo练习
1.简单的demo练习
@RestController
public class TestController {
//引入RedisTemplate模板
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping("/testRedis")
public void testRedis(){
//redis存入键值对
redisTemplate.opsForValue().set("1","存入key为1的值");
//根据key获取值
redisTemplate.opsForValue().get("1");
//当然也可以存入List,java对象什么的
redisTemplate.opsForValue().set("zhangsan",user);
System.out.println(list);
}
}
2.用于实际场景中(shiro为例)
这段代码是shiro的身份验证和权限验证,看不懂没关系,主要看redis使用场景
package com.braisedpanda.my.blog.web.config.shiro;
import com.alibaba.fastjson.JSONObject;
import com.braisedpanda.my.blog.commons.model.po.Role;
import com.braisedpanda.my.blog.commons.model.po.User;
import com.braisedpanda.my.blog.web.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
public class CustomRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Autowired
private RedisTemplate redisTemplate;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
User user = (User)principalCollection.getPrimaryPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//查询登录用户所拥有的角色,并添加角色
int id = user.getId();
/*******************************主要看这里**************************/
/************redis使用************/
//redis查出的格式是JSONObject,这里先转换成Role对象(如果查询的结果是某个对象的List<XXX>,则可以使用()List<XXX>)来强转,无需使用JSONObject类)
JSONObject jsonObject = (JSONObject) redisTemplate.opsForValue().get("AuthorizationInfo"+id);
Role role = JSONObject.toJavaObject(jsonObject,Role.class);
//如果role为null,说明redis并没有存储这个对象,那么从数据库中查询
if(role == null){
role = userService.getRole(id);
System.out.println("================开始权限查询================");
//把查出的结果存入redis,下次直接可以在redis中查询了,不必再次查询数据库
redisTemplate.opsForValue().set("AuthorizationInfo"+id,role);
}
/************redis结束************/
info.addRole(role.getRole());
return info;
}
//重写验证身份的方法
.....
在redis查到的role对象
使用redis之后,再次查询只会在内存中查询了,不会再调用数据库查询。因为对于那些查询结果固定的数据来说,在庞大的数据库中查询这些很浪费资源。比如一个用户的角色权限信息通常是不变的,第一次通过数据库查询之后,存入redis以便多次查询,可节约大量的资源。
参考与引用
1.Docker安装运行Redis
2.TemplateConfig.class,这个类我找不到源作者在哪了,如果无意侵犯,请联系立马删除