码迷,mamicode.com
首页 > 数据库 > 详细

springboot学习笔记-3 整合redis&mongodb

时间:2017-01-24 20:13:35      阅读:1092      评论:0      收藏:0      [点我收藏+]

标签:gson   tab   access   code   集合   文件属性   users   strategy   ima   

一.整合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的配置类

  在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配置文件

  技术分享

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

标签:gson   tab   access   code   集合   文件属性   users   strategy   ima   

原文地址:http://www.cnblogs.com/hlhdidi/p/6347719.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!