springboot学习笔记-3 整合redis&mongodb
一.整合redis
1.1 建立实体类
@Entity
@Table(name="user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date createDate; @JsonBackReference //防止json的重复引用问题
private Department department;
private Set<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 Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", createDate=" + createDate + ", department=" + department
+ ", roles=" + roles + "]";
} }
1.2 建立Redis的配置类
首先导入pom.xml相应的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
在springboot中,没有去提供直接操作Redis的Repository,但是我们可以使用RedisTemplate去访问Redis.想要去使用RedisTemplate,首先需要完成一些必要的配置.这里使用配置类去完成.
在application.properties中建立Redis的相关配置:

建立配置类,配置RedisTemplate,而要使用RedisTemplate还需要配置RedisConnectionFactory:
@ConfigurationProperties("application.properties")
@Configuration
public class RedisConfig {
@Value("${spring.redis.hostName}")
private String hostName;
@Value("${spring.redis.port}")
private Integer port;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory cf = new JedisConnectionFactory();
cf.setHostName(hostName);
cf.setPort(port);
cf.afterPropertiesSet();
return cf;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template=new StringRedisTemplate(factory);
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.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
1.3 建立UserRedis类,它实现了与Redis的交互
注意,在UserRedis中,使用了Redis的数据结构中最常用的key-value都是字符串的形式,采用Gson将对象转化为字符串然后存放到redis中.
@Repository
public class UserRedis {
@Autowired
private RedisTemplate<String, String> redisTemplate; public void add(String key,User user) {
Gson gson=new Gson();
redisTemplate.opsForValue().set(key,gson.toJson(user));
}
public void add(String key,List<User> users) {
Gson gson=new Gson();
redisTemplate.opsForValue().set(key,gson.toJson(users));
}
public User get(String key ) {
Gson gson=new Gson();
User user=null;
String userStr=redisTemplate.opsForValue().get(key);
if(!StringUtils.isEmpty(userStr))
user=gson.fromJson(userStr, 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);
}
}
1.4 建立UserController类
它自动注入了UserRedis类,通过不同的url实现了向redis存储数据,获取数据的功能.
@Controller
public class UserController {
@Autowired
UserRedis userRedis; @RequestMapping("/user/testRedisSave")
public String testRedis() {
Department department=new Department();
department.setName("开发部");
Role role=new Role();
role.setName("admin");
User user=new User();
user.setName("hlhdidi");
user.setCreateDate(new Date());
user.setDepartment(department);
Set<Role> roles=new HashSet<>();
roles.add(role);
user.setRoles(roles);
userRedis.delete(this.getClass().getName()+":username:"+user.getName());
userRedis.add(this.getClass().getName()+":username:"+user.getName(), user);
return null;
}
@RequestMapping("/user/testRedisGet")
public String testRedis2() {
User user=userRedis.get(this.getClass().getName()+":username:hlhdidi");
System.out.println(user);
return null;
}
}
先访问localhost:8080/user/testRedisSave,再访问localhost:8080/user/testRedisGet,即可测试成功!
二.整合MongoDB
MongoDB是一种文档类型的NoSql数据库.它内部有三个层次的概念,分别为数据库,集合,文档.使用springboot可以非常方便的整合MongoDB
2.1 建立mongo.properties配置文件

导入依赖:
<dependency>
<groupId>org.pegdown</groupId>
<artifactId>pegdown</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
2.2 建立MongoConfig配置类,完成对于MongoDB的配置
@Configuration
@EnableMongoRepositories(basePackages={"com.hlhdidi.springboot.mongo"})//MongoRepository的扫描包
@PropertySource("classpath:mongo.properties")//注入配置文件属性
public class MongoConfig extends AbstractMongoConfiguration{ @Autowired
private Environment env; @Override
protected String getDatabaseName() {
return env.getRequiredProperty("mongo.name");
} @Override
@Bean
public Mongo mongo() throws Exception {
ServerAddress serverAddress=new ServerAddress(env.getRequiredProperty("mongo.host"));
List<MongoCredential> credentials=new ArrayList<>();
return new MongoClient(serverAddress, credentials);
} }
2.3 建立SysUser实体类.
该实体类需要被存储到MongoDB数据库中.
@Document(collection="user")//配置collection的名称,如果没有将会自动建立对应的Collection
public class SysUser {
@Id
private String userId;
@NotNull @Indexed(unique=true)
private String username;
@NotNull
private String password;
@NotNull
private String name;
@NotNull
private String email;
@NotNull
private Date registrationDate=new Date();
private Set<String> roles=new HashSet<>();
public SysUser(){}
@PersistenceConstructor
public SysUser(String userId, String username, String password, String name, String email, Date registrationDate,
Set<String> roles) {
super();
this.userId = userId;
this.username = username;
this.password = password;
this.name = name;
this.email = email;
this.registrationDate = registrationDate;
this.roles = roles;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "SysUser [userId=" + userId + ", username=" + username + ", password=" + password + ", name=" + name
+ ", email=" + email + ", registrationDate=" + registrationDate + ", roles=" + roles + "]";
} }
2.4 建立SysUserRepository
由于springboot已经帮我们提供了操作MongoDB数据库的API,因此直接继承对应的类即可(和JPA一致)
@Repository
public interface SysUserRepository extends MongoRepository<SysUser, String>{ }
2.5 测试
测试类先向MongoDB中存储了一个实体类对象,随后获取指定对象的指定Collections下面的所有文档
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={MongoConfig.class})
@FixMethodOrder
public class MongoTest {
@Autowired
SysUserRepository repository; @Before
public void setup() {
Set<String> roles=new HashSet<>();
roles.add("manage");
SysUser sysUser=new SysUser("1", "hlhdidi", "123", "xiaohulong", "email@com.cn", new Date(), roles);
repository.save(sysUser);
}
@Test
public void findAll() {
List<SysUser> users=repository.findAll();
for(SysUser user:users) {
System.out.println(user);
}
}
}
springboot学习笔记-3 整合redis&mongodb的更多相关文章
- SpringBoot学习- 5、整合Redis
SpringBoot学习足迹 SpringBoot项目中访问Redis主要有两种方式:JedisPool和RedisTemplate,本文使用JedisPool 1.pom.xml添加dependen ...
- springboot学习笔记-4 整合Druid数据源和使用@Cache简化redis配置
一.整合Druid数据源 Druid是一个关系型数据库连接池,是阿里巴巴的一个开源项目,Druid在监控,可扩展性,稳定性和性能方面具有比较明显的优势.通过Druid提供的监控功能,可以实时观察数据库 ...
- Spring Boot 学习笔记(六) 整合 RESTful 参数传递
Spring Boot 学习笔记 源码地址 Spring Boot 学习笔记(一) hello world Spring Boot 学习笔记(二) 整合 log4j2 Spring Boot 学习笔记 ...
- SpringBoot学习笔记(10):使用MongoDB来访问数据
SpringBoot学习笔记(10):使用MongoDB来访问数据 快速开始 本指南将引导您完成使用Spring Data MongoDB构建应用程序的过程,该应用程序将数据存储在MongoDB(基于 ...
- SpringBoot学习笔记:Redis缓存
SpringBoot学习笔记:Redis缓存 关于Redis Redis是一个使用ANSI C语言编写的免费开源.支持网络.可基于内存亦可以持久化的日志型.键值数据库.其支持多种存储类型,包括Stri ...
- SpringBoot学习笔记
SpringBoot个人感觉比SpringMVC还要好用的一个框架,很多注解配置可以非常灵活的在代码中运用起来: springBoot学习笔记: .一.aop: 新建一个类HttpAspect,类上添 ...
- Springboot学习笔记(六)-配置化注入
前言 前面写过一个Springboot学习笔记(一)-线程池的简化及使用,发现有个缺陷,打个比方,我这个线程池写在一个公用服务中,各项参数都定死了,现在有两个服务要调用它,一个服务的线程数通常很多,而 ...
- SpringBoot学习笔记(14):使用SpringBootAdmin管理监控你的应用
SpringBoot学习笔记(14):使用SpringBootAdmin管理监控你的应用 Spring Boot Admin是一个管理和监控Spring Boot应用程序的应用程序.本文参考文档: 官 ...
- SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传
SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传 配置CKEDITOR 精简文件 解压之后可以看到ckeditor/lang下面有很多语言的js,如果不需要那么多种语言的,可 ...
随机推荐
- 所有权链(Ownership Chain)
所有权链(Ownership Chain)是特殊的权限评估方式,常见拥有所有权的数据库对象是:数据库对象,数据库角色(Role),和架构(Schema),在创建数据库角色,或架构时,SQL Serve ...
- $('#uplodFileForm')[0].submit();
jquery对象在[0]以下是取其相对应的Dom对象,即$("#mainForm")[0] = document.getElementById("mainForm&quo ...
- 为什么 Action/ViewController/ProperttyEditor不可见或不可用?
英文版:https://documentation.devexpress.com/eXpressAppFramework/112818/Concepts/Extend-Functionality/De ...
- SpringBoot日记——Thymeleaf模板引擎篇
开发通常我们都会使用模板引擎,比如:JSP.Velocity.Freemarker.Thymeleaf等等很多,那么模板引擎是干嘛用的? 模板引擎,顾名思义,是一款模板,模板中可以动态的写入一些参数, ...
- 一步步实现一个基本的缓存模块·续, 添加Memcached调用实现
jusfr 原创,转载请注明来自博客园. 在之前的实现中,我们初步实现了一个缓存模块:包含一个基于Http请求的缓存实现,一个基于HttpRuntime.Cache进程级的缓存实现,但观察代码,会发现 ...
- 【10.13】Bug Bounty Write-up 总结
今天惯例邮箱收到了Twitter的邮件提醒有新的post,这种邮件每天都能收到几封,正好看到一个Bug Bounty的write up,比较感兴趣,看起来也在我的理解范围之内,这里对这篇write u ...
- Babylon.js官方性能优化文档中文翻译
在这里列出Babylon.js官方性能优化文档的中英文对照,并在CardSimulate项目里对其中的一些优化方法进行实践. How To 如何 Optimize your scene 优化你的场景 ...
- FFmpeg+vs2013开发环境配置(windows)
1.下载ffmpeg包(dll.include.lib) https://ffmpeg.zeranoe.com/builds/ 有3个版本:Static.Shared和Dev St ...
- 记一次开发人员的奇葩操作-------导致root用户不能登录
首先,我表示国庆长假被开发呼叫,是一件很不开心的事...... 1.问开发,是不是/etc/passwd文件被更改了? 回答:没有 还好是新装的服务器,还好哥有服务器管理口的远程控制 单用户模式 ...
- 通过iLO进行Zabbix监控——针对HP服务器集成
iLO 全名是 Integrated Lights-out,它是惠普某些型号的服务器上集成的远程管理端口,它能够允许用户基于不同的操作系统从远端管理服务器,实现了虚拟存在和控制,从而进行智能型基础构架 ...