spring整合mongoDB 和 Redis 极简入门

mongoDB

简介

  • 文档Document 存储型 MongoDB
  • 图形关系存储型 Neo4j
  • 键值对存储redis
 docker run -d -p 27017:27017 mongo
  • 面向对象的思想,每一条数据记录 都是文档的对象
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency> //如果是本地连接,无需做任何配置

配置 MongoTemplate

  • 需要: MongoClient 和 MongoDbFactory
    @Bean//1,先配置 mongoClient
    public MongoClient client() throws UnknownHostException {
        //创建 MongoClient
        MongoClient client=new MongoClient(new ServerAddress("192.168.44.146",27017));
        return client;
    }

    @Bean//2,在配置mongoDb工厂
    public MongoDbFactory mongoDbFactory() throws Exception{
        //创建 database字符串
        String database = new MongoClientURI("mongodb://192.168.44.146/test").getDatabase();
        //返回 简单工程
        return new SimpleMongoDbFactory(client(),database);
    }

    @Bean//3,在配置mongo操作类
    public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory){
        //返回 template
        return new MongoTemplate(mongoDbFactory);
    }
	@Autowired
	MongoTemplate mongoTemplate;
	
	Person  p = new Person("wyf",32);
	mongoTemplate.save(p2);

repository支持 和配置

public interface PersonRepository extends MongoRepository<Person, String> {
	
	 Person findByName(String name);
	
	 @Query("{'age': ?0}") //查询参数构造json字符串
	 List<Person> withQueryFindByAge(Integer age);
}
@Configuration
@EnableMongoRepositories
spring:
  data:
    mongodb:
      host: 192.168.44.146 #主机地址
      port: 27017 #端口
      uri: mongodb://192.168.44.146/test #连接URL
      database: test #数据库
#      authentication-database: test
#      grid-fs-database: test
#      username: abc
#      password: abc
#      repositories:
#        enabled: true #是否开启 Repository,默认开启
#      field-naming-strategy: abc

领域模型

@Document //1 映射领域模型
public class Person {
	@Id
	private String id;
	private String name;
	private Integer age;
	@Field("locs") //此属性 在文档中 的名称为 locs
	private Collection<Location> locations =  new LinkedHashSet<Location>();
	
	//除了构造,还要有 get set
	public Person(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
}

public class Location {
	private String place;
	private String year;
	
}

action

@RestController
public class DataController {
	
	@Autowired
	PersonRepository personRepository;

	@RequestMapping("/save")
	public Person save(){
        
		Person  p = new Person("wyf",32);
        
        //曾经居住过 上海
		Collection<Location> locations =  new LinkedHashSet<Location>();
		Location loc1 = new Location("上海","2009");
		locations.add(loc1);
        
		//居住地 赋值
		p.setLocations(locations);
        
		return personRepository.save(p);
	}
	
	@RequestMapping("/q1")
	public Person q1(String name){
		return personRepository.findByName(name);
	}
	
	@RequestMapping("/q2")
	public List<Person> q2(Integer age){
		return personRepository.withQueryFindByAge(age);
	}

}

测试

http://localhost:8080/q1?name=张三
{
    "id": "61b0164148815a751ebb4048",
    "name": "张三",
    "age": 33,
    "locations": []
}


http://localhost:8080/q2?age=32
[
    {
        "id": "61b0213648810898b5b6c92f",
        "name": "wyf",
        "age": 32,
        "locations": [
            {
                "place": "上海",
                "year": "2009"
            },
            {
                "place": "合肥",
                "year": "2010"
            }
        ]
    }
]

[
    {
        "id": "61b0164148815a751ebb4048",
        "name": "张三",
        "age": 33,
        "locations": []
    }
]

redis

简介

  • Spring Data Redis
  • RedisTemplate
    • StringRedisTemplate 只针对 键值 都是字符型 的数据操作。
  • ConnectionFactory
    • Jedis ConnectionFactory
    • Jredis ConnectionFactory

引入 和 配置

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-redis</artifactId>
		</dependency>
    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        return new JedisConnectionFactory();
    }
    public RedisTemplate<Object, Object> redisTemplate(){
        RedisTemplate<Object,Object> template=new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory());
        return template;
    }

简单使用

	@Autowired
	RedisTemplate redisTemplate;

	ValueOperations valueOperations = redisTemplate.opsForValue();
	valueOperations.set("key123","456"); //执行完这句,即 存入redis

	// 放入后,20秒消失
	valueOperations.set("key123","456",20, TimeUnit.SECONDS);

opsFor开头的方法

  • Value() 简单属性的数据
  • List()
  • Set()
  • ZSet() 有序的set
  • Hash()

Serializer

  • RedisTemplate 用 Jdk Serialization Redis Serializer
  • StringRedisTemplate 用 String Redis Serializer

Spring Data JPA

  • generic To String Serializer
  • Jackson2 Json Redis Serializer 和 Jackson Json Redis Serializer
generic 
英 /dʒəˈnerɪk/  美 /dʒəˈnerɪk/  全球(美国)  
简明 牛津 新牛津  韦氏  柯林斯 例句  百科
adj. 类的;一般的;属的;非商标的
复数 generics比较级 more generic最高级 most generic

boot支持

  • RedisAutoConfiguration
  • JedisConnectionFactory
spring:
  redis:
    database: 0 #用0号库
    host: 192.168.44.146
#    password:
    port: 6379
#    pool:
#      max-idle: 8 #连接池数量
#      min-idle: 0 #最小
#      max-active: 8 #最大活跃
#      max-wait: -1 #最大等待,随意
#    sentinel:
#      master:
#      nodes:
#    timeout: 0 #超时

redis查看版本

docker exec -it port-redis(容器的名字) bash

redis-server --version
Redis server v=6.2.5 sha=00000000:0 malloc=jemalloc-5.1.0 bits=64 build=cc49a38120feeb6b

redis-cli -v
redis-cli 6.2.5

领域模型

  • 实现 序列化接口
  • 使用 jackson 要有 空构造
public class Person implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private String id;
	private String name;
	private Integer age;
	
	public Person() {
		super();
	}
	public Person(String id,String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
}

真实的使用

@Repository
public class PersonDao {
	
	/*@Autowired
	StringRedisTemplate stringRedisTemplate; //1
	@Autowired
	RedisTemplate<Object, Object> redisTemplate; //2*/
	
	@Resource(name="stringRedisTemplate")
	ValueOperations<String,String> valOpsStr; //3

	//使用 stringTemplate 放入
	public void stringRedisTemplateDemo(){ //5
        //ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        
		valOpsStr.set("xx", "yy");
	}
	//取出
	public String getString(){//7
		return valOpsStr.get("xx");
	}

	@Resource(name="redisTemplate")
	ValueOperations<Object, Object> valOps; //4
    
	//根据ID,放入 对象。
	public void save(Person person){ //6
        ValueOperations<Object, Object> operations = redisTemplate.opsForValue();
		valOps.set(person.getId(),person);
	}
	public Person getPerson(){//8
		return (Person) valOps.get("1");
	}

}

action

@RestController
public class DataController {
	
	@Autowired
	PersonDao personDao;

	@Autowired
	RedisTemplate redisTemplate;
	
	@RequestMapping("/set") //1
	public void set(){

		Person person = new Person("1","wyf", 32);
        //存入 person
		personDao.save(person);
        //放入 xx
		personDao.stringRedisTemplateDemo();
	}
	
	@RequestMapping("/getStr") //2
	public String getStr(){
		return personDao.getString();
	}
	
	@RequestMapping("/getPerson") //3
	public Person getPerson(){
		return personDao.getPerson();
	}
}

测试

  • 真实存入的 key 和 value
1
["com.wisely.ch8_6_2.dao.Person",{"id":"1","name":"wyf","age":32}]
http://localhost:8080/getPerson
{"id":"1","name":"wyf","age":32}

默认序列化更改

redisTemplate

  • 默认的是:Jdk Serialization Redis Serializer
  • 使用 二进制形式 存储数据

定义 Serializer

SuppressWarnings

作用:告诉编译器忽略指定的警告,不用在编译完成后出现警告信息。
    
@SuppressWarnings("unchecked")
告诉编译器忽略 unchecked 警告信息,如使用ListArrayList等未进行参数化产生的警告信息。

unchecked
取消与未检查的操作相关的警告
    
rawtypes
在类参数上使用泛型时,抑制与非特定类型相关的警告

   @SuppressWarnings("rawtypes")
   List items = new ArrayList();
   
   @SuppressWarnings(value={"unchecked", "rawtypes"})
public void addItems(String item){
   List items = new ArrayList();
   items.add(item);
 }
Suppress 
英 /səˈpres/  美 /səˈpres/  全球(英国)  
简明 牛津 新牛津  韦氏  柯林斯 例句  百科
v. (尤指用武力)镇压,压制;阻止(进程或活动);封锁,隐瞒(消息);抑制(生理过程);克制(感情或反应),忍住;部分(或完全)消除(电干扰);(心理分析)自觉抑制(不愉快的想法,记忆)
visibility 
英 /ˌvɪzəˈbɪləti/  美 /ˌvɪzəˈbɪləti/  全球(加拿大)  
简明 牛津 新牛津  韦氏  柯林斯 例句  百科
n. 能见度,能见距离;可见性,明显性;关注度,知名度

具体的配置

    @Bean //抑制 泛型 和 未检查 的警告
    @SuppressWarnings({ "rawtypes", "unchecked" }) //注入工厂
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
			throws UnknownHostException {
        //创建 template
		RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
		//设置 工厂
		template.setConnectionFactory(redisConnectionFactory);

		//创建 序列化的工具 为 :Jackson2Json
		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
		//创建 mapper
		ObjectMapper om = new ObjectMapper();
		// 设置能见度
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //打开 默认的 ,XXX
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        //jackson2 设置上 om
        jackson2JsonRedisSerializer.setObjectMapper(om);

        //template 设置上 jackson2 。值
        template.setValueSerializer(jackson2JsonRedisSerializer); //1
        //key 用 string
        template.setKeySerializer(new StringRedisSerializer()); //2
        //调用 之后 属性 设置
        template.afterPropertiesSet();
        //key 是 1。 value为:["com.wisely.ch8_6_2.dao.Person",{"id":"1", "name":"wyf", "age":32}]
		return template;
	}

返回到前端person对象:{"id":"1","name":"wyf","age":32}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值