springboot+redits
本可以快速上楼 却总在楼梯口磨磨蹭蹭,还是记录一下吧
环境 :window10 、IDEA 2018.2.4、jdk1.8.0_131 参考资料
redits简介 ①持久化于硬盘 ②key-val存储 ③存储速度块 量大。
一、搭配环境
1、下载redits:官网 -> 3.2.100 -> Assets4 -> Redis-x64-3.2.100.zip, 解压到E://Redis-x64-3.2.100目录下。
2、安装redits:用管理员方式打开cmd,①进入E://Redis-x64-3.2.100 ② 执行两条语句 启动redis。
E:\Redis-x64-3.2.100>redis-server --service-install redis.windows.conf --loglevel verbose --service-name redis --port 6379
E:\Redis-x64-3.2.100>net start redis
3、下载redisdesktopmanager可视化工具 百度网盘:双击 一路next
二、创建项目、两个配置
1、新建项目时对依赖包的选择:左边: NoSQL 右边: Spring Data Redits (Access+Driver)。或者直接在pom.xml中:
<dependency> <groupId>org.springframework.boot</groupId> <!--redis--> <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId> <!--JSON-->
<artifactId>fastjson</artifactId>
<version>1.1.23</version>
</dependency>
2、application.properties(放弃yml了)
# Redis数据库索引(默认为0)
spring.redis.database=1
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
#spring.redis.password=123456
#连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait= -1ms
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=300ms
3、目录结构与相关文件
三、如上图,建立包和类:
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; 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.*; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * redis配置类 * @program: springbootdemo * @Date: 2019/2/22 15:20 * @Author: zjjlive * @Description: */ @Configuration @EnableCaching //开启注解 public class RedisConfig extends CachingConfigurerSupport { /** * retemplate相关配置 * @param factory * @return */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); // 配置连接工厂 template.setConnectionFactory(factory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式) Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // 值采用json序列化 template.setValueSerializer(jacksonSeial); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); // 设置hash key 和value序列化模式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); return template; } /** * 对hash类型的数据操作 * * @param redisTemplate * @return */ @Bean public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForHash(); } /** * 对redis字符串类型数据操作 * * @param redisTemplate * @return */ @Bean public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForValue(); } /** * 对链表类型的数据操作 * * @param redisTemplate * @return */ @Bean public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForList(); } /** * 对无序集合类型的数据操作 * * @param redisTemplate * @return */ @Bean public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForSet(); } /** * 对有序集合类型的数据操作 * * @param redisTemplate * @return */ @Bean public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForZSet(); } }
public class Person {
private String name;
private String sex;
public Person() {
}
public Person(String name, String sex) {
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
1 public interface RedisService {
3 // set存数据 * @param key * @param value * @return
4 boolean set(String key, String value);
5
6 // get获取数据 * @param key * @return
7 String get(String key);
8
9 // 设置有效天数 * @param key * @param expire * @return
10 boolean expire(String key, long expire);
11
12 //移除数据 * @param key * @return
13 boolean remove(String key);
14 }
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@Service("redisService")
public class RedisServiceImpl implements RedisService {
@Resource
private RedisTemplate<String, ?> redisTemplate;
@Override
public boolean set(final String key, final String value) {
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
connection.set(serializer.serialize(key), serializer.serialize(value));
return true;
}
});
return result;
}
@Override
public String get(final String key) {
String result = redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
byte[] value = connection.get(serializer.serialize(key));
return serializer.deserialize(value);
}
});
return result;
}
@Override
public boolean expire(final String key, long expire) {
return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
@Override
public boolean remove(final String key) {
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
connection.del(key.getBytes());
return true;
}
});
return result;
}
}
说明: RedisService默认的key-value是16进制,RedisServiceImpl.java把它变成String。
2、鼠标移动到RedisServiceImpl.java文件中 implements RedisService代码处,alt+enter(键盘) -> create test
OK。
3、生成的RedisServiceImplTest.java 文件中有@Test,右击空白-> Run Test (如图二-3)程序将执行@Test注解的每一句代码。
import com.alibaba.fastjson.JSONObject;
import com.example.demo.Entity.Person;
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.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisServiceImplTest {
private JSONObject json = new JSONObject();
@Autowired
private RedisService redisService;
@Test
public void contextLoads() throws Exception {
}
/**
* 插入字符串
*/
@Test
public void setString() {
redisService.set("redis_string_test", "springboot redis test");
}
/**
* 获取字符串
*/
@Test
public void getString() {
String result = redisService.get("redis_string_test");
System.out.println(result);
}
/**
* 插入对象
*/
@Test
public void setObject() {
Person person = new Person("person", "male");
redisService.set("redis_obj_test", json.toJSONString(person));
}
/**
* 获取对象
*/
@Test
public void getObject() {
String result = redisService.get("redis_obj_test");
Person person = json.parseObject(result, Person.class);
System.out.println(json.toJSONString(person));
}
/**
* 插入对象List
*/
@Test
public void setList() {
Person person1 = new Person("person1", "male");
Person person2 = new Person("person2", "female");
Person person3 = new Person("person3", "male");
List<Person> list = new ArrayList<>();
list.add(person1);
list.add(person2);
list.add(person3);
redisService.set("redis_list_test", json.toJSONString(list));
}
/**
* 获取list
*/
@Test
public void getList() {
String result = redisService.get("redis_list_test");
List<String> list = json.parseArray(result, String.class);
System.out.println(list);
}
@Test
public void remove() {
redisService.remove("redis_test");
}
}
运行结果:
想想为什么是db1。
四、session
<dependency>
<groupId>org.springframework.session</groupId> <!--spring session-->
<artifactId>spring-session-data-redis</artifactId>
</dependency>
import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60)//默认是1800秒过期,这里测试修改为60秒 public class SessionConfig { }
@ResponseBody @RequestMapping("/uid") String uid(HttpSession session) { UUID uid = (UUID) session.getAttribute("uid"); if (uid == null) { uid = UUID.randomUUID(); } session.setAttribute("uid", uid); return session.getId(); }
五、闲谈
1、FastJson:阿里的开源框架,广受好评!
2、几个注解
@Service("name1") public class Impl_1 implements RedisService .... @Autowired
@Qualifier("name1") private RedisService RS; // _任意命名
①Spring自动扫描service包下的类,将@service注解的类注册到容器中;使用@Autowired时,Spring在容器中寻找。
②当RedisService有多个实现类Impl_1、Impl_2时,@Qualifier("name1")意指 RS用Impl_1实现。
2019-07-13 23:43:44

浙公网安备 33010602011771号