一.整合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的更多相关文章

  1. SpringBoot学习- 5、整合Redis

    SpringBoot学习足迹 SpringBoot项目中访问Redis主要有两种方式:JedisPool和RedisTemplate,本文使用JedisPool 1.pom.xml添加dependen ...

  2. springboot学习笔记-4 整合Druid数据源和使用@Cache简化redis配置

    一.整合Druid数据源 Druid是一个关系型数据库连接池,是阿里巴巴的一个开源项目,Druid在监控,可扩展性,稳定性和性能方面具有比较明显的优势.通过Druid提供的监控功能,可以实时观察数据库 ...

  3. Spring Boot 学习笔记(六) 整合 RESTful 参数传递

    Spring Boot 学习笔记 源码地址 Spring Boot 学习笔记(一) hello world Spring Boot 学习笔记(二) 整合 log4j2 Spring Boot 学习笔记 ...

  4. SpringBoot学习笔记(10):使用MongoDB来访问数据

    SpringBoot学习笔记(10):使用MongoDB来访问数据 快速开始 本指南将引导您完成使用Spring Data MongoDB构建应用程序的过程,该应用程序将数据存储在MongoDB(基于 ...

  5. SpringBoot学习笔记:Redis缓存

    SpringBoot学习笔记:Redis缓存 关于Redis Redis是一个使用ANSI C语言编写的免费开源.支持网络.可基于内存亦可以持久化的日志型.键值数据库.其支持多种存储类型,包括Stri ...

  6. SpringBoot学习笔记

    SpringBoot个人感觉比SpringMVC还要好用的一个框架,很多注解配置可以非常灵活的在代码中运用起来: springBoot学习笔记: .一.aop: 新建一个类HttpAspect,类上添 ...

  7. Springboot学习笔记(六)-配置化注入

    前言 前面写过一个Springboot学习笔记(一)-线程池的简化及使用,发现有个缺陷,打个比方,我这个线程池写在一个公用服务中,各项参数都定死了,现在有两个服务要调用它,一个服务的线程数通常很多,而 ...

  8. SpringBoot学习笔记(14):使用SpringBootAdmin管理监控你的应用

    SpringBoot学习笔记(14):使用SpringBootAdmin管理监控你的应用 Spring Boot Admin是一个管理和监控Spring Boot应用程序的应用程序.本文参考文档: 官 ...

  9. SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传

    SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传 配置CKEDITOR 精简文件 解压之后可以看到ckeditor/lang下面有很多语言的js,如果不需要那么多种语言的,可 ...

随机推荐

  1. 使用VS Code新建编译Flutter项目

    本文的前提是你已经安装好了VS Code,并且安装了Flutter和Dart扩展插件. 1. 新建Flutter项目 查看——命令面板,或者Ctrl + Shift + P 输入 Flutter: N ...

  2. web测试通用要点大全(Web Application Testing Checklist)

    在测试工作中经常遇到测试同一控件功能的情景,这样几年下来也积累了各种测试功能控件的checklist,过年期间抽空整理分享出来.通过下面的清单,任何测试新手都可以快速写出媲美工作好几年的测试老鸟的测试 ...

  3. 记一个小bug的锅

    人生中的第一个线上bug 我参与的第一个项目就出现了.但是自己还觉得这锅也不全是自己的,毕竟那么明显的bug出现在历史模块中(不是我写的新模块),难道测试部就没一点责任?代码走查人员就没一点责任?不过 ...

  4. Mysql行转列的简单应用

    最近在复习过程中愈发觉得,有些东西久了不用,真的会忘~——~. 将上面的表格转换为下面的表格 我拼sql拼了好久还是没弄出来,还是偶然看到我以前的笔记,才想起有行转列这样的操作(太久没有写过复杂点的s ...

  5. 图形 - bootStrap4常用CSS笔记

    .rounded 图片显示圆角效果 .rounded-circle 设置椭圆形图片 .img-thumbnail 设置图片缩略图(图片有边框) .img-fluid 响应式图片 .float-righ ...

  6. 有序链表转换二叉搜索树(LeetCode)

    将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树. 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1. 示例: 给定有序数组: [-10,-3,0, ...

  7. appium+python+unittest 测试用例的几种加载执行方式

    利用python进行测试时,测试用例的加载方式有2种: 一种是通过unittest.main()来启动所需测试的测试模块:  一种是添加到testsuite集合中再加载所有的被测试对象,而testsu ...

  8. oozie捕获标准输出&异常capture-output

    对于普通的java-action或者shell-action 都是支持的只要标准输出是"k1=v1"这中格式的就行: 现用test.py进行测试: ##test.py #! /op ...

  9. GitHub笔记(二)——远程仓库的操作

    二 远程仓库 1 创建联系 第1步:创建SSH Key.在用户主目录下,看看有没有.ssh目录,如果有,再看看这个目录下有没有id_rsa和id_rsa.pub这两个文件,如果已经有了,可直接跳到下一 ...

  10. redis使用Jackson2JsonRedisSerializer序列化问题

    一.spring boot 集成Redis方法 依赖 <!--redis--> <dependency> <groupId>org.springframework. ...