Spring Boot + Redis
启动redis
docker run --name redisServer -P -d redis
redis自带客户端,启动客户端
docker run -it --link redisServer:db --entrypoint redis-cli redis -h db
也可以使用桌面工具Redis Desktop Manager测试
下载地址:https://redisdesktop.com/download
下载完后安装,打开程序
连接服务器
可以看到上面存进去的name
新建一个Spring Boot项目,pom.xml如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion> <groupId>org.mythsky</groupId>
<artifactId>spring-boot-redis-demo</artifactId>
<version>0.0.-SNAPSHOT</version>
<packaging>jar</packaging> <name>spring-boot-redis-demo</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.</version>
</dependency> <!--<dependency>-->
<!--<groupId>springboot.db</groupId>-->
<!--<artifactId>mysql</artifactId>-->
<!--<version>${project.version}</version>-->
<!--</dependency>-->
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
添加User
package org.mythsky.springbootredisdemo.domain; import java.io.Serializable;
import java.util.Date;
import java.util.List; public class User implements Serializable {
private Long id;
private String name;
private Date createDate;
private Department department;
private List<Role> roles; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Date getCreateDate() {
return createDate;
} public void setCreateDate(Date createDate) {
this.createDate = createDate;
} public Department getDepartment() {
return department;
} public void setDepartment(Department department) {
this.department = department;
} public List<Role> getRoles() {
return roles;
} public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
Department
package org.mythsky.springbootredisdemo.domain; import java.io.Serializable; public class Department implements Serializable {
private Long id;
private String name; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
Role
package org.mythsky.springbootredisdemo.domain; import java.io.Serializable; public class Role implements Serializable {
private Long id;
private String name; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
RedisConfig
package org.mythsky.springbootredisdemo.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.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; @Configuration
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory(){
JedisConnectionFactory redisConnectionFactory=new JedisConnectionFactory();
redisConnectionFactory.setHostName("192.168.31.146");
redisConnectionFactory.setPort();
redisConnectionFactory.setUsePool(true);
return redisConnectionFactory;
}
@Bean
public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory factory){
StringRedisTemplate template=new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper=new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
UserRedis
package org.mythsky.springbootredisdemo.service; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.mythsky.springbootredisdemo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils; import java.util.List;
import java.util.concurrent.TimeUnit; @Repository
public class UserRedis {
@Autowired
private RedisTemplate<String,String> redisTemplate; public void add(String key,Long time,User user){
Gson gson=new Gson();
redisTemplate.opsForValue().set(key,gson.toJson(user),time, TimeUnit.MINUTES);
} public void add(String key, Long time, List<User> users){
Gson gson=new Gson();
redisTemplate.opsForValue().set(key,gson.toJson(users),time, TimeUnit.MINUTES);
} public User get(String key){
Gson gson=new Gson();
User user=null;
String userJson=redisTemplate.opsForValue().get(key);
if(!StringUtils.isEmpty(userJson)){
user=gson.fromJson(userJson,User.class);
}
return user;
} public List<User> getList(String key){
Gson gson=new Gson();
List<User> users=null;
String listJson=redisTemplate.opsForValue().get(key);
if(!StringUtils.isEmpty(listJson)){
users=gson.fromJson(listJson,new TypeToken<List<User>>(){}.getType());
}
return users;
} public void delete(String key){
redisTemplate.opsForValue().getOperations().delete(key);
}
}
SpringBootRedisDemoApplicationTests
package org.mythsky.springbootredisdemo; import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mythsky.springbootredisdemo.config.RedisConfig;
import org.mythsky.springbootredisdemo.domain.Department;
import org.mythsky.springbootredisdemo.domain.Role;
import org.mythsky.springbootredisdemo.domain.User;
import org.mythsky.springbootredisdemo.service.UserRedis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList;
import java.util.Date;
import java.util.List; @RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRedisDemoApplicationTests { private static Logger logger= LoggerFactory.getLogger(SpringBootRedisDemoApplicationTests.class);
@Autowired
UserRedis userRedis;
@Before
public void setup(){
Department department=new Department();
department.setName("开发部"); Role role=new Role();
role.setName("admin"); User user=new User();
user.setName("user");
user.setCreateDate(new Date());
user.setDepartment(department); List<Role> roles=new ArrayList<Role>();
roles.add(role); user.setRoles(roles); userRedis.delete(this.getClass().getName()+":userByName:"+user.getName());
userRedis.add(this.getClass().getName()+":userByName:"+user.getName(),10l,user);
}
@Test
public void get() {
User user=userRedis.get(this.getClass().getName()+":userByName:user");
Assert.assertNotNull(user);
logger.info("======user====== name:{}, department:{}, role:{}",user.getName(),user.getDepartment(),user.getRoles().get().getName());
} }
运行,可以在测试窗口看到结果
此时再打开桌面客户端
连接redis集群
官方文档:
最主要的是设置RedisConnectionFactory
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
config
@Component
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class ClusterConfigurationProperties { /*
* spring.redis.cluster.nodes[0] = 127.0.0.1:7379
* spring.redis.cluster.nodes[1] = 127.0.0.1:7380
* ...
*/
List<String> nodes; /**
* Get initial collection of known cluster nodes in format {@code host:port}.
*
* @return
*/
public List<String> getNodes() {
return nodes;
} public void setNodes(List<String> nodes) {
this.nodes = nodes;
}
}
@Configuration
public class AppConfig { /**
* Type safe representation of application.properties
*/
@Autowired
ClusterConfigurationProperties clusterProperties;
@Value("${spring.redis.password}")
private String password; public @Bean
RedisConnectionFactory connectionFactory() {
RedisClusterConfiguration configuration=new RedisClusterConfiguration(clusterProperties.getNodes());
configuration.setPassword(RedisPassword.of(password));
return new JedisConnectionFactory(configuration);
}
}
配置文件
spring.redis.cluster.nodes=172.20.102.65:7001,172.20.102.65:7002,172.20.102.65:7003,172.20.102.66:7004,172.20.102.66:7005,172.20.102.66:7006
spring.redis.password=123456
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisDemoApplicationTests { @Test
public void contextLoads() {
String result= stringRedisTemplate.opsForValue().get("api:tmp:users:1375bf2a-8e03-4097-8e1f-803787b6fac2");
System.out.println(result);
}
@Test
public void test1(){
String result=redisTemplate.opsForValue().get("api:tmp:users:1375bf2a-8e03-4097-8e1f-803787b6fac2");
System.out.println(result);
}
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String,String> redisTemplate;
}
Spring Boot + Redis的更多相关文章
- spring boot redis缓存JedisPool使用
spring boot redis缓存JedisPool使用 添加依赖pom.xml中添加如下依赖 <!-- Spring Boot Redis --> <dependency> ...
- spring boot + redis 实现session共享
这次带来的是spring boot + redis 实现session共享的教程. 在spring boot的文档中,告诉我们添加@EnableRedisHttpSession来开启spring se ...
- Spring Boot 项目学习 (三) Spring Boot + Redis 搭建
0 引言 本文主要介绍 Spring Boot 中 Redis 的配置和基本使用. 1 配置 Redis 1. 修改pom.xml,添加Redis依赖 <!-- Spring Boot Redi ...
- Spring Boot Redis 集成配置(转)
Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...
- spring boot redis 缓存(cache)集成
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- spring boot redis分布式锁
随着现在分布式架构越来越盛行,在很多场景下需要使用到分布式锁.分布式锁的实现有很多种,比如基于数据库. zookeeper 等,本文主要介绍使用 Redis 做分布式锁的方式,并封装成spring b ...
- 从.Net到Java学习第四篇——spring boot+redis
从.Net到Java学习系列目录 “学习java已经十天,有时也怀念当初.net的经典,让这语言将你我相连,怀念你......”接上一篇,本篇使用到的框架redis.FastJSON. 环境准备 安装 ...
- Spring Boot Redis Cluster 实战干货
添加配置信息 spring.redis: database: 0 # Redis数据库索引(默认为0) #host: 192.168.1.8 #port: 6379 password: 123456 ...
- Spring boot redis自增编号控制 踩坑
近段期间,公司 接手一个订单号生成服务,规则的话已经由项目经理他们规定好了,主要是后面的四位数代表的关于当前订单号已经执行第几个了.而这里面有一个要求就是支持分布式.为了实现这个东西,刚开始我使用了r ...
随机推荐
- Codeforces Round #265 (Div. 2) E. Substitutes in Number
http://codeforces.com/contest/465/problem/E 给定一个字符串,以及n个变换操作,将一个数字变成一个字符串,可能为空串,然后最后将字符串当成一个数,取模1e9+ ...
- Visualise the Argyris basis functions
""" Author: kinnala Visualise the Argyris basis functions. """ from sk ...
- 如何在js里引用php变量
如何在js里面引用php的变量 php代码------------------------------------------- js代码------------------------------- ...
- Android-Genymotion Unable to load VirtualBox engine
点击Genymotion出现Genymotion Unable to load VirtualBox engine 解决方案: 打开官网,下载VirtualBox 点击安装: 然后再次点击打开Geny ...
- Kali Linux渗透测试实战 2.1 DNS信息收集
目录 2.1 DNS信息收集1 2.1.1 whois查询3 2.1.2 域名基本信息查询4 Dns服务器查询4 a记录查询4 mx记录查询5 2.1.3 域名枚举5 fierse 5 dnsdict ...
- 通过键盘控制改变物体transform值
通过键盘控制改变物体transform值 private Vector3 trans; //使用Rotate绕y 轴旋转 transform.Rotate(new Vector3(0,Input.Ge ...
- 通过JS拦截 pushState 和 replaceState 事件
history.pushState 和 history.replaceState 可以在不刷新当前页面的情况下更改URL,但是这样就无法获取通过AJAX得到的新页面的内容了.虽然各种HTML5文档说 ...
- 在我朝如何为Brackets安装扩展?
Brackets是Adobe发起的一个开源的HTML编辑器,界面优美简洁.扩展丰富.支持基于Chrome浏览器的实时预览,非常适合对于Web的开发和学习. 但是Brackets的安装包下载和扩展下载, ...
- 背水一战 Windows 10 (42) - 控件(导航类): Frame 动画
[源码下载] 背水一战 Windows 10 (42) - 控件(导航类): Frame 动画 作者:webabcd 介绍背水一战 Windows 10 之 控件(导航类) Frame 动画 示例An ...
- lua编程之lua与C相互调用
lua是扩展性非常良好的语言,虽然核心非常精简,但是用户可以依靠lua库来实现大部分工作.除此之外,lua还可以通过与C函数相互调用来扩展程序功能.在C中嵌入lua脚本既可以让用户在不重新编译代码的情 ...